String key = Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
System.out.println(key);
Set<Entry<String,Integer>> entrySet = countMap.entrySet();
Collections.max(countMap.entrySet());
这里第一行代码"Collections.max(Collection<?extends T>, Comparator<? super T>)
"将两个参数作为 Set 和比较器,工作正常。
但是最后一行代码"Collections.max(countMap.entrySet());
"给出了编译时错误,说">集合类型中的max(Collection(方法不适用于参数(Set>("。 需要对上述提及代码进行解释。
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max(java.util.Collection( 有
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
集合中的所有元素都必须实现可比较接口。
Entry
不实现 Comparable 接口,因此无法将其传递给此方法。
extends
...T
类型参数的约束中的Comparable
是告知编译器有关要求的内容。