ComputeIfPresent Example in Java

HashMap computeIfPresent() method in Java with Examples

The computeIfPresent(Key, BiFunction) method of HashMap class is used to update value in a key-value pair in the map. If key does not exist then it does not do any thing.

Syntax

undefined
V computeIfPresent(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) 

Example

Following is an example of computeIfAbsent invocation and its results.
ComputeIfAbsentExample
package corejava.map;

import java.util.HashMap;
import java.util.Map;

public class ComputeIfPresentExample {

	public static void main (String argv[]) {
		
		Map<String, Integer> map = new HashMap<String, Integer>();

		map.put("Sunglass", 105);
		map.put("Watch", 1501);
		
		
		newline("Original Map");
		map.forEach((a, b) -> {
			System.out.println(a + " -> " + b);
		});
		
		
		map.computeIfPresent("Watch", (k,v) -> {return v + v;});
		
		newline("After calling computeIfAbsent Map");
		map.forEach((a, b) -> {
			System.out.println(a + " -> " + b);
		});
	}
	
	static void newline(String s) {
		System.out.println("\n" + s);
	};
}
Output of above program.
Original Map
Watch -> 1501
Sunglass -> 105

After calling computeIfAbsent Map
Watch -> 3002
Sunglass -> 105

Summary

computeIfPresent helps in writing more compact code and also make code more readable.

No comments :

Post a Comment

Please leave your message queries or suggetions.