java获取map大小_java – 从HashMap获取最大Set大小
我有一個< Integer,Set< Integer>>的hashMap.
我愿意使用java流操作獲取具有最大大小的Set.
這是我的例子:
public class Example {
public static void main( String[] args ) {
Map> adj = new HashMap<>();
Set set1 = Stream.of(1,2,3).collect(Collectors.toSet());
Set set2 = Stream.of(1,2).collect(Collectors.toSet());
adj.put(1,set1);
adj.put(2,set2);
}
}
我試過這個:
Collections.max(adj,Comparator.comparingInt(Set::size));
但我收到編譯錯誤,因為Set接口中的size()方法不是靜態的.
通常我們應該得到3作為最大尺寸設置.
解決方法:
您不能使用Map< Integer,Set< Integer>>與Collection.max.因為它被定義為采取集合.
public static T max(Collection extends T> coll, Comparator super T> comp)
因此,為了使其工作,要么:
Collections.max(adj.values(), Comparator.comparingInt(Set::size));
或者流:
adj.values()
.stream()
.max(Comparator.comparingInt(Set::size));
標簽:java,java-8,java-stream,hashmap,set
來源: https://codeday.me/bug/20190727/1549040.html
總結
以上是生活随笔為你收集整理的java获取map大小_java – 从HashMap获取最大Set大小的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c#打包mysql配置文件_C#打包SQ
- 下一篇: java 怎么判别注释符_java学习笔