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());
Run Code Online (Sandbox Code Playgroud)
这里第一行代码" 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)
Run Code Online (Sandbox Code Playgroud)
集合中的所有元素都必须实现Comparable接口.
Entry 没有实现Comparable接口,因此您无法将其传递给此方法.
类型参数的约束中的extends... 是告诉编译器有关需求的内容.ComparableT
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |