0

Hi I have the following HashMap

HashMap<String, Integer> normalised = new HashMap<String, Integer>();

and would like to print out the highest value in the map and its associated key.

Could anyone help I tried using the following code to no avail

        String maxKey=null;
        int maxValue = Interger.MIN_VALUE; 
        for(Map.Entry<String,Integer> entry : normalised.entrySet()) {
            if(entry.getValue() > maxValue) {
             maxValue = entry.getValue();
             maxKey = entry.getKey();
        }
    }

Can someone guide to as where I am going wrong

Thanks in advance

3 Answers3

1
Map.Entry<String, Integer> maxEntry = null;
for (Map.Entry<String, Integer> entry :normalised.entrySet()){
    if (maxEntry == null ||entry.getValue().compareTo(maxEntry.getValue()) > 0){
        maxEntry = entry;
    }
}

If there are multiple keys with same maximum values though, you will get the first key with the max value.

Artur Filipiak
  • 9,027
  • 4
  • 30
  • 56
djames
  • 366
  • 5
  • 17
0

Your example works if you correct the typo "Interger" to "Integer". See also: https://stackoverflow.com/a/5911199/4602991

Community
  • 1
  • 1
wfr
  • 661
  • 5
  • 12
0

This should work fine :

HashMap<String, Integer> normalised = new HashMap<String, Integer>();
String maxKey=null;
long maxValue = Integer.MIN_VALUE; 
for(String key : normalised.keySet()) {
    if(normalised.get(key).longValue() > maxValue) {
        maxValue = entry.getValue().longValue();
        maxKey = entry.getKey();
    }
}
StackFlowed
  • 6,664
  • 1
  • 29
  • 45