Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java map.get(key) - automatically do put(key) and return if key doesn't exist?

I am sick of the following pattern:

value = map.get(key); if (value == null) {     value = new Object();     map.put(key, value); } 

This example only scratches the surface of the extra code to be written when you have nested maps to represent a multi-dimensional structure.

I'm sure something somewhere exists to avoid this, but my Googling efforts yielded nothing relevant. Any suggestions?

like image 560
Sridhar Sarnobat Avatar asked Nov 30 '11 22:11

Sridhar Sarnobat


People also ask

What does map get return if key is not present?

Map get() method If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.

What if HashMap does not contain key?

Since there is a ! before the expression, this means "if the map does not contain a key". After that, "then" block follows where you insert a key in the map with value 1 (since it does not exist).

Can a map hold a null key?

Yes, null is always a valid map key for any type of map key (including primitives, sobjects, and user-defined objects).


1 Answers

The

java.util.concurrent.ConcurrentMap  

and from Java 8

Java.util.Map 

has

putIfAbsent(K key, V value)  

which returns the existing value, and if that is null inserts given value. So if no value exists for key returns null and inserts the given value, otherwise returns existing value

If you need lazy evaluation of the value there is

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) 
like image 162
Roger Lindsjö Avatar answered Sep 18 '22 19:09

Roger Lindsjö