Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Puzzling about how computeIfAbsent works to update duplicate key->list value pair

From this guide,
computeIfAbsent is used to create and update the value list, but how is it achieved?

Here for

map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2");

I was expecting no updates since key1 exist, however it ends up adding "value2" to the value list

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Map<String, List<String>> map = new HashMap<>();
map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1");
map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2");

assertThat(map.get("key1").get(0)).isEqualTo("value1");
assertThat(map.get("key1").get(1)).isEqualTo("value2");

>Solution :

In the given code, computeIfAbsent() is used to check if a given key exists in the map. If the key is not present in the map, computeIfAbsent() creates a new entry with the key and a new ArrayList as the value. If the key is already present in the map, computeIfAbsent() returns the value corresponding to the key.

In the given code, the map is defined as a HashMap with String keys and List values. The code then calls computeIfAbsent() twice for the same key "key1". The first call adds "value1" to the new ArrayList created by computeIfAbsent(), and the second call adds "value2" to the same ArrayList.

So even though "key1" already exists in map, computeIfAbsent() still returns the existing ArrayList value associated with "key1", and "value2" is added to the same ArrayList.

The assertThat() statements are then used to verify that "value1" and "value2" were added to the List at the expected indices.

In summary, the computeIfAbsent() method is used to ensure that a key exists in the map and to provide a default value if the key does not exist. If the key already exists, then computeIfAbsent() returns the existing value associated with the key.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading