Home > database >  Iteration on keyset of HashMap
Iteration on keyset of HashMap

Time:10-06

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.

CodePudding user response:

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

p. s. Sorry for my bad English

  • Related