简体   繁体   中英

Iteration on keyset of HashMap

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 .

You can try to manually find max value by iterating entry set like that

HashMap.Entry<String, Integer> maxEntry = new AbstractMap.SimpleEntry<String, Integer>("temp", -1);
for(HashMap.Entry<String, Integer> entry : players.entrySet()) {
    if(entry.getValue() > maxEntry.getValue()) {
        maxEntry = entry;
    }
}
System.out.println(maxEntry);

Entry is a pair of values: key and value.

When you iterate Map you get next entry in iteration, so you can get value from entry by getValue() method and compare it with exiting value in temporary variable (maxEntry).

You can get values from Entry to format output like:

System.out.println("Name: " + maxEntry.getKey() + " Age: " + maxEntry.getValue());

ps Sorry for my bad English

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM