我有一个< 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