Advertisement here

Difference between computeIfAbsent vs getOrDefault in Java

Advertisement here




Both getOrDefault() and computeIfAbsent() are methods in Java that are used to retrieve values from a hashmap. However, there are some differences between the two.

getOrDefault() is used to get the value associated with the specified key. If the key is not present in the hashmap, it returns the default value specified by the user. The syntax of the getOrDefault() method is:

hashmap.getOrDefault(K key, V defaultValue)

Here, hashmap is the hashmap in which we want to retrieve the value. K is the key whose associated value is to be retrieved. V defaultValue is the default value that will be returned if the key is not present in the hashmap.

On the other hand, computeIfAbsent() is used to compute a new value and associate it with the specified key if the key is not associated with any value in the hashmap. The syntax of the computeIfAbsent() method is:

hashmap.computeIfAbsent(K key, Function remappingFunction)

Here, hashmap is the hashmap in which we want to insert the new value. K is the key whose associated value is to be computed. Function remappingFunction is a function that computes the new value.

The difference between these two methods is that getOrDefault() will accept an existing instance (created before the method is invoked) and return it if needed but will not add it to the map . On the other hand, computeIfAbsent() accepts a function for lazily creating a new value and will also add that value to the map .

 Here is an example:


Map<String, Integer> map = new HashMap<>();

map.put("apple", 1);

map.put("banana", 2);


// Using getOrDefault()

int appleCount = map.getOrDefault("apple", 0);

int orangeCount = map.getOrDefault("orange", 0);


System.out.println("Apple count: " + appleCount); // Output: Apple count: 1

System.out.println("Orange count: " + orangeCount); // Output: Orange count: 0

Copy

On the other hand, computeIfAbsent() is used to compute a new value and associate it with the specified key if the key is not associated with any value in the hashmap. Here is an example:


Map<String, List<String>> map = new HashMap<>();

map.computeIfAbsent("fruits", k -> new ArrayList<>()).add("apple");

map.computeIfAbsent("fruits", k -> new ArrayList<>()).add("banana");


System.out.println(map.get("fruits")); // Output: [apple, banana]





Next Post Previous Post
No Comment
Add Comment
comment url