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.

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.

Remove all entries in map by value

Java Map is a data structure that holds key->value pairs. In this article we will see how to delete all entries in the map by map values.

Using removeAll

removeAll() takes one argument a collection. And entries matching the passed collection will be removed from the original map
Using removeAll
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");
map.put(6, "five");

newline("Original Map");
map.values().removeAll(Collections.singleton("five"));

newline("After removing values = five");
map.forEach( (a,b) -> {
	System.out.println(a + " -> " + b);
});
Output of above program.
Original Map
1 -> one
2 -> two
3 -> three
4 -> four
5 -> five
6 -> five
7 -> five

After removing values = five
1 -> one
2 -> two
3 -> three
4 -> four

Using removeIf

removeIf
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");
map.put(6, "five");

newline("Original Map");

//remove entries where value = five
map.values().removeIf("five"::equals);

newline("After removing values = five");
map.forEach( (a,b) -> {
	System.out.println(a + " -> " + b);
});
Output of above program.
Original Map
1 -> one
2 -> two
3 -> three
4 -> four
5 -> five
6 -> five
7 -> five

After removing values = five
1 -> one
2 -> two
3 -> three
4 -> four

Remove all entries from java map

Java Map is a data structure that holds key->value pairs. In this article we will see how to delete all entries in the map in java easily and efficetively.

Method clear()

clear() method is method that does not return any thing (void return type) and is part of the Map interface. Each implementation subclasses provides an implementation. clear () methods deleted all entries and turn them map into empty map.
Clear method
static void clearALLItemsInMap() {
		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");
		map.put(6, "five");
		
		newline("Original Map");
		map.forEach( (a,b) -> {
			System.out.println( a + " -> " + b);
		});
		
                 //clear the map
		map.clear();
		
		newline("After classing clear() Map");
		map.forEach( (a,b) -> {
			System.out.println(a + " -> " + b);
		});
	}
Output of above program.
Original Map
1 -> one
2 -> two
3 -> three
4 -> four
5 -> five
6 -> five

After classing clear() Map
empty

Summary

For removing all the entries from java map, clear() method is the best option. Also please note that the clear() method is implemented in each of its implementation classes like, HashMap, TreeMap, LinkedHashMap etc.

How to iterate Java Map

Java Map can be iterated various ways to go over all the key:value pairs
Create Map and add some values
Map<Integer, String> map = new HashMap<>();
map.put(1,"Argentina");
map.put(2,"France");
map.put(3,"Brazil");
map.put(4,"Germany");
Using EntrySet Iterator
//EntrySet Iterator
System.out.println("\nEntrySet foreach");
Iterator<Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext()) {
    Map.Entry<Integer, String> keyVal = it.next();
    System.out.println(keyVal.getKey() + " " + keyVal.getValue());
}
Using EntrySet and foreach
//EntrySet and foreach
System.out.println("\nEntrySet foreach");
Set<Entry<Integer, String>> entrySet = map.entrySet();
entrySet.forEach((e-> { System.out.println(e.getKey() + " " + e.getValue());}));
Using Keyset Iterator
//Keyset Iterator
System.out.println("\nKeyset Iterator");
Iterator<Integer> kit = map.keySet().iterator();
while(kit.hasNext()) {
    Integer key = kit.next();
	System.out.println(key + " " + map.get(key));
}
Keyset For loop
//Keyset For loop
System.out.println("\nKeyset For loop");
for (Integer key : map.keySet()) {
	System.out.println(key + " " + map.get(key));
}
Using Java 8 Lambda
//map foreach (Java 8 Lambda)
System.out.println("\nUsing Map.foreach (Java 8 Lambda");
map.forEach((key,value)-> {System.out.println(key + " " + value);});

Summary

Here I have covered 5 different ways to iterate over Java Map and access both key and values.

How to Sort HashMap in java

This article covers some of the aspects of sorting Map in Java. Java Map comes in different flavours, like HashMap, TreeMap, LinkedHashMap etc. TreeMap for instance will sort the data based on the keys. We can also pass a custom Comparator to sort based on the keys as per the custom sort algorithm.
We can have two requirements in terms of sorting, first one is sorting by Keys and second is Sorting by Values. Following examples demonstrates few approaches for sorting by key and sorting by value. Following examples uses Java Lambda and Stream api to sort Java HashMap instance.

Sort by Value

Map sort by value in revere order
Following code snippet sorts the map based on value in reverse order and populates a new map reverseSortedMap from the data.
//LinkedHashMap preserve the ordering of elements in which they are inserted
Map reverseSortedMap =  new LinkedHashMap();
//Use Comparator.reverseOrder() for reverse ordering
map.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) 
    .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));

Sort By Key

Map sort by key in revere order
Following code snippet sorts the map based on the keys in reverse order.
//LinkedHashMap preserve the ordering of elements in which they are inserted
Map reverseSortedMapByKey =  new LinkedHashMap();;
//Use Comparator.reverseOrder() for reverse ordering
map.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 
    .forEachOrdered(x -> reverseSortedMapByKey.put(x.getKey(), x.getValue()));
 

System.out.println("Sorted by Value Map : " + reverseSortedMapByKey);

Full Example

MapSortJava
public class MapSortJava {

  public static void main(String[] args) {

    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(101, "Tokyo");
    map.put(3, "New York");
    map.put(2, "San Francisco");
    map.put(14, "Los Angels");
    map.put(5, "Austin");

    System.out.println("Unsorted Map : " + map);
    
   // LinkedHashMap preserve the ordering of elements in which they are inserted
    Map<Integer, String> reverseSortedMap = new LinkedHashMap<Integer, String>();;
    // Use Comparator.reverseOrder() for reverse ordering
    map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
    System.out.println("Sorted by Value Map : " + reverseSortedMap);


    // LinkedHashMap preserve the ordering of elements in which they are inserted
    Map<Integer, String> reverseSortedMapByKey = new LinkedHashMap<Integer, String>();;
    // Use Comparator.reverseOrder() for reverse ordering
    map.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
        .forEachOrdered(x -> reverseSortedMapByKey.put(x.getKey(), x.getValue()));
    System.out.println("Sorted by Value Map : " + reverseSortedMapByKey);

  }
}
Output
Unsorted Map : 2 ==> San Francisco 3 ==> New York 101 ==> Tokyo 5 ==> Austin 14 ==> Los Angels Sorted by Value Map (Reverse) : 2 ==> San Francisco 3 ==> New York 101 ==> Tokyo 5 ==> Austin 14 ==> Los Angels Sorted by Value Map (Reverse) : 101 ==> Tokyo 14 ==> Los Angels 5 ==> Austin 3 ==> New York 2 ==> San Francisco
Summary of steps
  • Get the entry set by calling the Map.entrySet().
  • Get the entry set stream by calling stream() method.
  • Use the Map.Entry.comparingByValue() or Map.Entry.comparingByKey().
  • Call the sorted method with a Comparator.
  • call the terminal operation forEachOrdered to store the each entries in the new Map.

How to use custom comparator for TreeMap

This article covers some of the aspects of sorting Map in Java. Java Map comes in different flavors, like HashMap, TreeMap, LinkedHashMap etc. TreeMap for instance will sort the data based on the keys. We can also pass a custom Comparator to sort based on the keys as per the custom sort algorithm.
TreeMap sorts based on natural ordering of the keys if no custom Comparator is provided. To use a custom Comparator we need to pass the Comparator in the TreeMap Constructor.

Simple TreeMap

TreeMap without any Comparator
Following code creates a TreeMap and adds some data to it. After that we print the TreeMap. As No comparator is specified, the data is sorted by natural ordering of the keys.
TreeMap map = new TreeMap();
    map.put(1, "A");
    map.put(3, "C");
    map.put(2, "B");
    map.put(4, "D");
    map.put(5, "E");


    System.out.println("\nPrint Map ");
    map.forEach((a, b) -> {
      printKeyVal(a,b);
    });;
Print Map Key: 1 Value: A Key: 2 Value: B Key: 3 Value: C Key: 4 Value: D Key: 5 Value: E

TreeMap with Comparator

TreeMap with reverse order Comparator
In this case we are passing a built in Comparator to sort the keys reversely. From the result we can see that the data is sorted in reverse order of the keys.
System.out.println("\nPrint Map with Reverse Comparator");
TreeMap map2 = new TreeMap(Collections.reverseOrder());
    map2.putAll(map);
    map2.forEach((a, b) -> {
      printKeyVal(a, b);
 });
Print Map with Reverse Comparator Key: 5 Value: E Key: 4 Value: D Key: 3 Value: C Key: 2 Value: B Key: 1 Value: A

Custom Comparator

Following examples shows implementation of two custom Comparator, one with inner class second one with java 8 Lambda. Both the Comparator works exactly same, that is it sorts the data in reverse order.
With Inner Classes
Custom Comparator with Inner Class to sort the keys in reverse order.
Comparator orderByKeyDesc = new Comparator() {
@Override
 public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
      }
};
Lambda Comparator.
Java 8 Lambda to implement Comparator
Comparator orderByKeyDesc2 = (Integer o1, Integer o2) -> o2.compareTo(o1);

Full Example

TreeMapCustomComparator
Full example with Custom Comparator that is passed to the TreeMap.
public class TreeMapCustomComparator {

  public static void main(String[] args) {

    TreeMap map = new TreeMap();
    map.put(1, "A");
    map.put(3, "C");
    map.put(2, "B");
    map.put(4, "D");
    map.put(5, "E");


    System.out.println("\nPrint Map ");
    map.forEach((a, b) -> {
      printKeyVal(a, b);
    });;

   
    System.out.println("\nPrint Map with Reverse Comparator");
    TreeMap map2 = new TreeMap(Collections.reverseOrder());
    map2.putAll(map);
    map2.forEach((a, b) -> {
      printKeyVal(a, b);
    });


    //Custom Comparator with Inner Class
    Comparator orderByKeyDesc = new Comparator() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
      }
    };

    //Custom Comparator with Lambda
    Comparator orderByKeyDesc2 = (Integer o1, Integer o2) -> o2.compareTo(o1);

    System.out.println("\nPrint Map with Custom Reverse Comparator Java Lambda");
    TreeMap map3 = new TreeMap(orderByKeyDesc2);
    map3.putAll(map);

    map3.forEach((a, b) -> {
      printKeyVal(a, b);
    });

  }

  /* Utility method to print key value pairs nicely */
  private static void printKeyVal(Object a, Object b) {
    System.out.print("Key: " + a + "  Value: " + b + "     ");
  }


}
Print Map Key: 1 Value: A Key: 2 Value: B Key: 3 Value: C Key: 4 Value: D Key: 5 Value: E Print Map with Reverse Comparator Key: 5 Value: E Key: 4 Value: D Key: 3 Value: C Key: 2 Value: B Key: 1 Value: A Print Map with Custom Reverse Comparator Java Lambda Key: 5 Value: E Key: 4 Value: D Key: 3 Value: C Key: 2 Value: B Key: 1 Value: A

Table of Content

Iterating Java Map

Java Map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. If we want to get the object stored at a particular key we can do so using the the get method.
But if we want to traverse all the objects, then we have different ways of doing the same.

Different Options

In Java we have the following four options to iterate over java map.
Map Iterator
Classic way of using the Iterator of the keySet.
//Iterator
Map map = new TreeMap();
System.out.println("Print using Iterator");
Iterator it = map.keySet().iterator();

while (it.hasNext()) {
  Integer k = it.next();
  String  v = map.get(k);
  System.out.print( "Key=" + k + " Value=" + v + "  ");
}
Java 8 forEach
We can use the forEach introduced in Java 8 to iterate over key and value.
//forFeach
Map map = new TreeMap();
System.out.println("\nPrint using Java 8 forEach");
map.forEach((k,v) -> System.out.print("Key=" + k + " Value=" + v + "  "));
For loop over the keyset
Using for loop over the key set, and then getting the respective value from the map.
//For loop over the keySet
Map map = new TreeMap();
System.out.println("\nPrint using for loop");
for (Integer k : map.keySet()) {
  String  v = map.get(k);
  System.out.print("Key=" + k + " Value=" + v + "  ");
}

Full Example

Full Java Class with all the above options to iterate over map.
MapIterationExample
package bootng.com.learn.collections;

public class MapIterationExample {
  public static void main(String[] args) {
    Map<Integer, String> map = new TreeMap<Integer, String>();
    map.put(1, "A");
    map.put(3, "C");
    map.put(2, "B");
    map.put(4, "D");
    map.put(5, "E");

    // Iterator
    System.out.println("Print using Iterator");
    Iterator<Integer> it = map.keySet().iterator();

    while (it.hasNext()) {
      Integer k = it.next();
      String v = map.get(k);
      System.out.print("Key=" + k + " Value=" + v + "  ");
    }

    // forFeach
    System.out.println("\nPrint using Java 8 forEach");
    map.forEach((k, v) -> System.out.print("Key=" + k + " Value=" + v + "  "));

    // For loop over the keySet
    System.out.println("\nPrint using for loop");
    for (Integer k : map.keySet()) {
      String v = map.get(k);
      System.out.print("Key=" + k + " Value=" + v + "  ");
    }

    // Stream
    System.out.println("\nPrint using stream");
    map.keySet().stream().forEach(key -> {
      System.out.print("Key=" + key + " Value=" + map.get(key) + "  ");
    });    
  }
}
Output
Print using Iterator
Key=1 Value=A  Key=2 Value=B  Key=3 Value=C  Key=4 Value=D  Key=5 Value=E  
Print using Java 8 forEach
Key=1 Value=A  Key=2 Value=B  Key=3 Value=C  Key=4 Value=D  Key=5 Value=E  
Print using for loop
Key=1 Value=A  Key=2 Value=B  Key=3 Value=C  Key=4 Value=D  Key=5 Value=E  
Print using stream
Key=1 Value=A  Key=2 Value=B  Key=3 Value=C  Key=4 Value=D  Key=5 Value=E  

Table of Content

removeEldestEntry() Method in Java

LinkedHashMap in Java stores key-value pairs and maintains the order of elements inserted. LinkedHashMap extends HashMap. Method removeEldestEntry in LinkedHashMap is used to delete the old entry in the map automatically. This method is triggered when we put values to the map.
removeEldestEntry() method is triggered when we put new items to map. It is a boolean method and accepts one parameter. We can override this method to decide whether and when to remove eldest entries from the map.

Examples

LinkedHashMap Simple
Following is a simple LinkedHashMap which is created with initial size 10. And then later added 6 Items to it. When we print the map it prints {0=A, 1=B, 2=C, 3=D, 4=E, 5=F}
LinkedHashMap map;
map = new LinkedHashMap(10 , 0.7f, false);
map.put(0, "A"); 
map.put(1, "B"); 
map.put(2, "C"); 
map.put(3, "D"); 
map.put(4, "E"); 
map.put(5, "F");

System.out.println(map); //{0=A, 1=B, 2=C, 3=D, 4=E, 5=F}
LinkedHashMap with removeEldestEntry
Here we implement the protected method removeEldestEntry and return true if size is more than 4. As a result this map will automatically delete one of the oldest entry when its size becomes more than 4. That's why even though we are adding 6 items to it, when we print we get only 4 items like {2=C, 3=D, 4=E, 5=F}
LinkedHashMap map;

map = new LinkedHashMap(10 , 0.7f, false) {
  protected boolean removeEldestEntry(Map.Entry eldest) {
    return size()>4;
  }
};

map.put(0, "A"); 
map.put(1, "B"); 
map.put(2, "C"); 
map.put(3, "D"); 
map.put(4, "E"); 
map.put(5, "F");

System.out.println(map); //{2=C, 3=D, 4=E, 5=F}
Notes
  • LinkedHashMap maintains the insertion order of the values.
  • If removeEldestEntry returns false then no items will ever be removed from the map and it will essentially behave like a normal Map.
  • If removeEldestEntry returns true then it will not let any item's get added to the map.
  • removeEldestEntry is a protected method that's why we can only implement it while creating the map.