computeifabsent Example in Java map

HashMap computeIfAbsent() method in Java with Examples

The computeIfAbsent(Key, Function) method of HashMap class is used to enter a new key-value pair to map if the key does not exist. If key exists then it does not do any thing.

Syntax

undefined
public V computeIfAbsent(K key, Function<? super K, ? 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 ComputeIfAbsentExample {

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

		map.put(1, "one");
		map.put(2, "two");
		map.put(3, "three");
		map.put(4, "four");
		map.put(5, "five");
		
		newline("Original Map");
		map.forEach((a, b) -> {
			System.out.println(a + " -> " + b);
		});
		
		map.computeIfAbsent(6, k-> { return "six";});
		map.computeIfAbsent(7, k -> "seven");
		
		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
1 -> one
2 -> two
3 -> three
4 -> four
5 -> five

After calling computeIfAbsent Map
1 -> one
2 -> two
3 -> three
4 -> four
5 -> five
6 -> six
7 -> seven

Summary

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

No comments :

Post a Comment

Please leave your message queries or suggetions.