从 HashMap 中获取最大 Set 大小

3

我有一个<Integer, Set<Integer>>的hashMap。

我希望使用Java流操作获取元素数量最大的Set。

以下是我的示例:

public class Example {

     public static void main( String[] args ) {
         Map<Integer,Set<Integer>> adj = new HashMap<>();
         Set<Integer> set1 = Stream.of(1,2,3).collect(Collectors.toSet());
         Set<Integer> 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的集合。

2个回答

4

如果您使用的是 Map<Integer,Set<Integer>>,则无法使用 Collection.max。因为它被定义为使用 Collection。

public static <T> 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));

3
我们应该得到最大尺寸为3的集合。
要获取map中Set的最大大小,您可以使用以下代码:
int maxSetSize = adj.values()
        .stream()
        .max(Comparator.comparingInt(Set::size))
        .map(Set::size)
        .orElse(0);

1
… .mapToInt(Set::size).max() … ... .mapToInt(Set::size).max() ... - Holger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接