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
?
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With