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

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

Remove an entry with Largest Value in a HashMap :

To remove an entry with Largest Value,

  • First sort the HashMap in descendingorder of Values
  • Then get the 1st entry from the reversesorted 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 Largest Value from HashMap

  • Using Java 8 Stream
  • Before Java 8

1. Using Java 8 Stream :

  • First step is to sort the Map entries in descendingorder of Values which will give an entry with Largest Value at the top of the Map
    • To sort Map entries in descending-order of Values, use Stream.sorted() method passing the argument Map.Entry.comparingByValue(Comparator.reverseOrder())
  • Get the 1st entry from sorted Map using Stream.findFirst() method
  • Finally, remove the 1st entry by comparing the Largest 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 largest then all duplicates will be removed

RemoveEntryWithLargestValueInMapUsingJava8Stream.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 RemoveEntryWithLargestValueInMapUsingJava8Stream {

	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> entryWithLargestValue = countryPopulation
				.entrySet()
				.stream()
				.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
				.findFirst()
				.get();


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



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


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


		// 3.2 print Map entries after removing entry with Largest 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 Largest Value :- Indian=382357386


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

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

2. Before Java 8 :

  • First step is to sort the Map entries in descendingorder of Values which will give an entry with Largest Value at the top of the Map
    • To sort Map entries in descendingorder of Values, convert HashMap to TreeMap passing Comparator object with reverseorder 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 Largest Value obtained from the previous step using remove() method

RemoveEntryWithLargestValueInMap.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 RemoveEntryWithLargestValueInMap {

	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 descending-order of Values
		Map<String, Integer> treeMapInDescValues = new TreeMap<>(new Comparator<String>() {

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


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


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


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

			// first entry will be largest, as it sorted in descending-order of Values
			if(null == entryWithLargestValue) {
				entryWithLargestValue = entry;
				break;
			}
		}


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



		// 3. remove entry with Largest Value
		countryPopulation
		.values()
		.remove(entryWithLargestValue.getValue());


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


		// 3.1 print Map entries after removing entry with Largest 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 Largest Value :- Indian=382357386


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

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

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java 8 - How to find an entry with Smallest Key in a Map or HashMap ?
Java 8 - How to find an entry with Largest Value in a Map or HashMap ?