joe hashahm
joe hashahm

Reputation: 1

Print out the key and maximum value in a hashmap

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

Upvotes: 0

Views: 1272

Answers (3)

djames
djames

Reputation: 366

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.

Upvotes: 1

StackFlowed
StackFlowed

Reputation: 6816

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();
    }
}

Upvotes: 0

wfr
wfr

Reputation: 701

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

Upvotes: 0

Related Questions