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
?
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"