Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map implementation that returns a default value instead of null

Tags:

java

default

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?

like image 947
jk. Avatar asked Jan 28 '11 21:01

jk.


People also ask

What is default value of map in Java?

Since the hashmap does not contain any mapping for key 4 . Hence, the default value Not Found is returned. Note: We can use the HashMap containsKey() method to check if a particular key is present in the hashmap.

Does map allow null values in Java?

It doesn't allow nulls. So consider using a TreeMap when you want a Map sorts its key-value pairs by the natural order of the keys. Points to remember: Map doesn't allow duplicate keys, but it allows duplicate values.

Does map get return null?

The most important Map function is map. get(key) which looks up the value for a key and returns it. If the key is not present in the map, get() returns null.


1 Answers

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" 
like image 144
Jeffrey Avatar answered Oct 08 '22 02:10

Jeffrey