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
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.