HashMap键集上的java迭代
我很难迭代hashmap并将具有最大整数的键集返回到hashmap中。。。我举个例子,谁能给我解释一下怎么做,谢谢
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 */
}
}
}
我只需要打印按键集Luigi
# 1 楼答案
方法^{} 需要一个
Collection
,并将返回其最大元素,在集合的内部元素上迭代。因此,没有必要在自己的代码中将其与循环结合起来当你的起点是一个} 是正确的选择
Map
而不是一个Collection
时,你需要决定一个视图,keySet()
、entrySet()
或values()
来传递给那个方法。因为您需要两者,比较的值和最终结果的键,^{因为} ,这正是您想要的
entrySet()
的类型是Set<Map.Entry<String, Integer>>
,换句话说,它是一个没有实现Comparable
的元素集合,所以需要指定一个Comparator
。接口Map.Entry
已经提供了方便的内置比较器,比如^{所以,使用^{} 的完整解决方案是
当然,您也可以手动迭代
entrySet()
,并识别this answer中的最大元素