Examples of using Default Methods introduced in Java 8 in Map interface

  1. Using getOrDefault

Returns the value mapped to the key, or if the key is not present, returns the default value

Map<Integer, String> map = new HashMap<>();
map.put(1, "First element");
map.get(1);                                 // => First element
map.get(2);                                 // => null
map.getOrDefault(2, "Default element");     // => Default element
  1. Using forEach

Allows to perform the operation specified in the ‘action’ on each Map Entry

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.forEach((key, value) -> System.out.println("Key: "+key+ " :: Value: "+value));

 // Key: 1 :: Value: one
 // Key: 2 :: Value: two
 // Key: 3 :: Value: three
  1. Using replaceAll

Will replace with new-value only if key is present

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("john", 20);
map.put("paul", 30);
map.put("peter", 40);
map.replaceAll((key,value)->value+10);   //{john=30, paul=40, peter=50}
  1. Using putIfAbsent

Key-Value pair is added to the map, if the key is not present or mapped to null

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("john", 20);
map.put("paul", 30);
map.put("peter", 40);
map.putIfAbsent("kelly", 50);     //{john=20, paul=30, peter=40, kelly=50}
  1. Using remove

Removes the key only if its associated with the given value

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("john", 20);
map.put("paul", 30);
map.put("peter", 40);
map.remove("peter",40); //{john=30, paul=40}
  1. Using replace
If the key is present then the value is replaced by new-value. 
If the key is not present, does nothing.
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("john", 20);
map.put("paul", 30);
map.put("peter", 40);
map.replace("peter",50); //{john=20, paul=30, peter=50}
map.replace("jack",60); //{john=20, paul=30, peter=50}
  1. Using computeIfAbsent