I have difficulty to iterate hashmap and return the keyset with the maximum integer into an HashMap...I leave an example can anyone explain me how to do, thanks.
import java.util.*;
public class Program {
public static void main(String[ ] args) {
HashMap <String, Integer> players = new HashMap<String, Integer>();
players.put("Mario", 27);
players.put("Luigi", 43);
players.put("Jack", 11);
//my problem goes here
for (HashMap.Entry <String, Integer> f : players.entrySet()) {
System.out.println (Collections.max(f));
/*
/usercode/Program.java:13: error: no suitable method found for
max(Entry<String,Integer>)
System.out.println (Collections.max(f));
^
method Collections.<T#1>max(Collection<? extends T#1>) is not applicable
(cannot infer type-variable(s) T#1
(argument mismatch; Entry<String,Integer> cannot be converted to Collection<? extends
T#1>))
method Collections.<T#2>max(Collection<? extends T#2>,Comparator<? super T#2>) is not
applicable
(cannot infer type-variable(s) T#2
(actual and formal argument lists differ in length))
where T#1,T#2 are type-variables:
T#1 extends Object,Comparable<? super T#1> declared in method <T#1>max(Collection<?
extends T#1>)
T#2 extends Object declared in method <T#2>max(Collection<? extends T#2>,Comparator<?
super T#2>)
1 error */
}
}
}
I need it print only keyset Luigi.
The method Collections.max(…)
expects a Collection
and will return its maximum element, iterating over the collection’s elements internally. Therefore, there is no need to combine it with a loop in your own code.
When your starting point is a Map
, which is not a Collection
, you need to decide for a view, keySet()
, entrySet()
, or values()
, to pass into that method. Since you need both, the value for the comparison and the key for the final result, entrySet()
is the right choice.
Since the entrySet()
has the type Set<Map.Entry<String, Integer>>
, in other words, is a collection of elements not implementing Comparable
, you need to specify a Comparator
. The interface Map.Entry
does already provide convenient built-in comparators, like Map.Entry.comparingByValue()
which is what you want.
So, the complete solution using Collections.max(…)
is
System.out.println(
Collections.max(players.entrySet(), Map.Entry.comparingByValue()).getKey()
);
Of course, you can also iterate over the entrySet()
manually and identify the maximum element like in this answer.