How to find Entry with largest value in Java Map

In this section, we will find the key with maximum value for a given HashMap.Basically, HashMap is used to store <Key, Value> pair in which all the keys are unique.

Approach to the problem:

  • We will iterate over every <key, value> pair, and then compare the value of each pair with the current maximum value.
  • If the value of the key is greater than the current maximum value, we will update the current maximum as that of value and store the key associated with that value.
  • If the value of the key is less than or equal to the current maximum value, we will simply move onto the next entry.
  • After completion of the enhanced for loop, we will be having entry with maximum value.

Java program to find Entry with the largest value in Java Map

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

public class maxElement {

  public static void main(String[] args) {
    int max=Integer.MIN_VALUE;
    String name=null;
    
    //Creating HashMap
    HashMap<String,Integer> map=new HashMap<>();
    map.put("Physics", 72);
    map.put("English",34);
    map.put("Chemistry", 60);
    map.put("Economics", 55);
    map.put("Maths", 80);
    
    //System.out.println(map);
    
    //Traversing over every value of Map
    Set<Map.Entry<String,Integer>> entries=map.entrySet();
    for(Entry<String,Integer> entry:entries) {
      if(entry.getValue()>max) {
        max=entry.getValue();
        name=entry.getKey();
      }
    }
    
    System.out.print("Entry with the highest value: "+name);
    
  }
}

In the above code, we have first created HashMap, according to the requirement you can change its data type and values, after that we have taken up an entrySet to store <key, value> pair of HashMap so that we can traverse over each and every value. For traversing purpose we have taken up an “enhanced for loop”, you can take normal “for loop” as well and then find the corresponding output.

OUTPUT:

Entry with the highest value: Maths

Leave a Reply