// Java program to Find Entry // with the Highest Value in Map // Using Comparators in Map interface
// Importing all utility classes import java.util.*;
// Main class classGFG {
// Method 1 // Find the entry with highest value publicstatic <K, V extendsComparable<V> > Map.Entry<K, V> getMaxEntryInMapBasedOnValue(Map<K, V> map) {
// To store the result Map.Entry<K, V> entryWithMaxValue = null;
// Iterate in the map to find the required entry for (Map.Entry<K, V> currentEntry : map.entrySet()) {
if ( // If this is the first entry, set result as // this entryWithMaxValue == null
// If this entry's value is more than the // max value Set this entry as the max || currentEntry.getValue().compareTo( entryWithMaxValue.getValue()) > 0) {
entryWithMaxValue = currentEntry; } }
// Return the entry with highest value return entryWithMaxValue; }
// Method 2 // To print the map publicstaticvoidprint(Map<String, Integer> map) {
System.out.print("Map: ");
// If map does not contain any value if (map.isEmpty()) {
// Method 3 // Main driver method publicstaticvoidmain(String[] args) {
// Creating a Map // Declaring object of string and integer type Map<String, Integer> map = newHashMap<>();
// Inserting elements in the Map object // using put() method // Custom input element addition map.put("ABC", 10); map.put("DEF", 30); map.put("XYZ", 20);
// Calling method 2 to // print the map print(map);
// Calling method 1 to // find the entry with highest value and // print on the console System.out.println( "Entry with highest value: " + getMaxEntryInMapBasedOnValue(map)); } }
Output:
1 2
Map: {ABC=10, DEF=30, XYZ=20} Entry with highest value: DEF=30
Method 2: Using max() method from Collections class without lambda expression
// Using Collections.max() method returning max // value in HashMap and storing in a integer // variable int maxValueInMap = (Collections.max(map.values()));
// Iterate through HashMap for (Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == maxValueInMap) {
// Print the key with max value System.out.println(entry.getKey()); } } } }
Output:
1
3
Method 3: Using the concept of Streams introduced in Java 8