Java 8 – How to remove an entry with Smallest Value in a Map or HashMap ?

In this article, we will discuss how to remove an entry with Smallest Value in a HashMap using Java 8 Stream

Remove an entry with Smallest Value in a HashMap :

To remove an entry with Smallest Value,

  • First sort the HashMap in ascendingorder of Values
  • Then get the 1st entry from the naturalsorted Map
  • Finally, remove the 1st entry by comparing the Value

There are different ways to sort the Map/HashMap according to Values, read below articles before proceeding further

Here, we will discuss only 2 approaches to remove an entry with Smallest Value from HashMap

  • Using Java 8 Stream
  • Before Java 8

1. Using Java 8 Stream :

  • First step is to sort the Map entries in ascendingorder of Values which will give an entry with Smallest Value at the top of the Map
    • To sort Map entries in ascending-order of Values, use Stream.sorted() method passing the argument Map.Entry.comparingByValue(Comparator.naturalOrder())
  • Get the 1st entry from sorted Map using Stream.findFirst() method
  • Finally, remove the 1st entry by comparing the Smallest Value obtained from the previous step using removeIf() method
  • Note: if there are duplicate values present for the different unique keys and if it happens to be smallest then all duplicates will be removed

RemoveEntryWithSmallestValueInMapUsingJava8Stream.java

package in.bench.resources.find.entry.map;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class RemoveEntryWithSmallestValueInMapUsingJava8Stream {

	public static void main(String[] args) {

		// 1. creating HashMap object of type <String, Integer>
		Map<String, Integer> countryPopulation = new HashMap<>(); 


		// 1.1 adding key-value pairs to HashMap object
		countryPopulation.put("Pakistan", 220892331);
		countryPopulation.put("Russia", 146748590);
		countryPopulation.put("Brazil", 213728559);
		countryPopulation.put("Indian", 382357386);
		countryPopulation.put("America", 332429717);


		// 1.2 print original Map entries
		System.out.println("1. Original Map Entries :- \n");


		// 1.3 print Map entries to console
		countryPopulation.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));



		// 2. Sort Values using Java 8 Stream.sorted() method & get 1st Entry
		Entry<String, Integer> entryWithSmallestValue = countryPopulation
				.entrySet()
				.stream()
				.sorted(Map.Entry.comparingByValue(Comparator.naturalOrder()))
				.findFirst()
				.get();


		// 2.2 print Map.Entry with Smallest Value
		System.out.println("\n\n2. Map Entry with Smallest Value :- " + entryWithSmallestValue);



		// 3. remove entry with Smallest Value
		countryPopulation
		.entrySet()
		.removeIf(entry -> entry.getValue().equals(entryWithSmallestValue.getValue()));


		// 3.1 print to console
		System.out.println("\n\n3. Map entries after removing entry with Smallest Value :- \n");


		// 3.2 print Map entries after removing entry with Smallest Value
		countryPopulation.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));
	}
}

Output :

1. Original Map Entries :- 

Key : Pakistan		Value : 220892331
Key : America		Value : 332429717
Key : Brazil		Value : 213728559
Key : Indian		Value : 382357386
Key : Russia		Value : 146748590


2. Map Entry with Smallest Value :- Russia=146748590


3. Map entries after removing entry with Smallest Value :- 

Key : Pakistan		Value : 220892331
Key : America		Value : 332429717
Key : Brazil		Value : 213728559
Key : Indian		Value : 382357386

2. Before Java 8 :

  • First step is to sort the Map entries in ascendingorder of Values which will give an entry with Smallest Value at the top of the Map
    • To sort Map entries in ascendingorder of Values, convert HashMap to TreeMap passing Comparator object with naturalorder sorting logic as constructorargument to TreeMap
  • Get the 1st entry from sorted Map by iterating using enhanced forloop and then break the loop
  • Finally, remove the 1st entry by comparing the Smallest Value obtained from the previous step using remove() method

RemoveEntryWithSmallestValueInMap.java

package in.bench.resources.find.entry.map;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class RemoveEntryWithSmallestValueInMap {

	public static void main(String[] args) {

		// 1. creating HashMap object of type <String, Integer>
		Map<String, Integer> countryPopulation = new HashMap<>(); 


		// 1.1 adding key-value pairs to HashMap object
		countryPopulation.put("Pakistan", 220892331);
		countryPopulation.put("Russia", 146748590);
		countryPopulation.put("Brazil", 213728559);
		countryPopulation.put("Indian", 382357386);
		countryPopulation.put("America", 332429717);


		// 1.2 print original Map entries
		System.out.println("1. Original Map Entries :- \n");


		// 1.3 print Map entries to console
		countryPopulation.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));



		// 2. convert HashMap to TreeMap in ascending-order of Values
		Map<String, Integer> treeMapInAscValues = new TreeMap<>(new Comparator<String>() {

			@Override
			public int compare(String str1, String str2) {
				return countryPopulation.get(str1).compareTo(countryPopulation.get(str2));
			}
		});


		// 2.1  add unsorted map to TreeMap for natural-order sorting of Values
		treeMapInAscValues.putAll(countryPopulation);


		// 2.2 local variable to assign Entry with Smallest Value
		Entry<String, Integer> entryWithSmallestValue = null;


		// 2.3 iterate and get 1st entry from natural-sorted Map
		for(Entry<String, Integer> entry : treeMapInAscValues.entrySet()) {

			// first entry will be smallest, as it sorted in ascending-order of Values
			if(null == entryWithSmallestValue) {
				entryWithSmallestValue = entry;
				break;
			}
		}


		// 2.4 print Map.Entry with Smallest Value
		System.out.println("\n\n2. Map Entry with Smallest Value :- " + entryWithSmallestValue);



		// 3. remove entry with Smallest Value
		countryPopulation
		.values()
		.remove(entryWithSmallestValue.getValue());


		// 3.1 print to console
		System.out.println("\n\n3. Map entries after removing entry with Smallest Value :- \n");


		// 3.1 print Map entries after removing entry with Smallest Value
		countryPopulation.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));
	}
}

Output :

1. Original Map Entries :- 

Key : Pakistan		Value : 220892331
Key : America		Value : 332429717
Key : Brazil		Value : 213728559
Key : Indian		Value : 382357386
Key : Russia		Value : 146748590


2. Map Entry with Smallest Value :- Russia=146748590


3. Map entries after removing entry with Smallest Value :- 

Key : Pakistan		Value : 220892331
Key : America		Value : 332429717
Key : Brazil		Value : 213728559
Key : Indian		Value : 382357386

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java 8 – How to find an entry based on the Key in a Map or HashMap ?
Java 8 - How to find an entry with Smallest Value in a Map or HashMap ?