Java Map implementation that returns a default value instead of null

jk. picture jk. · Jan 28, 2011 · Viewed 26.9k times · Source

I have a Map<String, List<String>> in my code, where I'd avoid potential null pointers if the map's #get() method returned an empty list instead of null. Is there anything like this in the java API? Should I just extend HashMap?

Answer

Jeffrey picture Jeffrey · Apr 9, 2014

Thanks to default methods, Java 8 now has this built in with Map::getOrDefault:

Map<Integer, String> map = ...
map.put(1, "1");
System.out.println(map.getOrDefault(1, "2")); // "1"
System.out.println(map.getOrDefault(2, "2")); // "2"