【发布时间】:2019-03-31 06:22:38
【问题描述】:
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());”给出了编译时错误“Collection 类型中的方法 max(Collection) 不适用于参数 (Set>)”。
需要对上述代码进行解释。
【问题讨论】:
-
提供
countMap -
这两个哪个条目更大? 1:
"abc" -> 1000; 2:"CBA" -> 0。你知道吗? Java 没有。Collections.max方法采用Comparable的集合。集合中的元素必须是Comparable,或者您需要提供一个Comparator来定义如何比较元素。
标签: java collections