Reputation: 1
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
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
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
Reputation: 701
Your example works if you correct the typo "Interger" to "Integer". See also: https://stackoverflow.com/a/5911199/4602991
Upvotes: 0