加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java-8 – 集合流到新集合的交集

发布时间:2020-12-15 00:47:16 所属栏目:Java 来源:网络整理
导读:对这个问题有更好,更简单的方法吗? @Testpublic void testReduce() { SetInteger foo = ImmutableSet.of(1,2,3,4,8,9); SetInteger bar = ImmutableSet.of(1,5,11); //DO think about solution for 1..n sets,and not only two. SetInteger intersection =
对这个问题有更好,更简单的方法吗?
@Test
public void testReduce() {
    Set<Integer> foo = ImmutableSet.of(1,2,3,4,8,9);
    Set<Integer> bar = ImmutableSet.of(1,5,11);

    //DO think about solution for 1..n sets,and not only two.
    Set<Integer> intersection = ImmutableList.of(foo,bar)
            .stream()
            .reduce( null,(a,b) -> {
                if ( a == null ) {
                    a = new HashSet<Integer>(b);
                }
                else {
                    a.retainAll(b);
                }
                return a;
            });
    assertThat( intersection,is( ImmutableSet.of( 1,8) ) );
}

解决方法

reduce是错误的方法,因为不允许以这种方式修改函数的参数.这是一个可变的减少,也称为收集:
List<Set<Integer>> listOfSets=…;
//check if at least one set is in the list
Set<Integer> intersection = listOfSets.stream().skip(1)
    .collect(()->new HashSet<>(listOfSets.get(0)),Set::retainAll,Set::retainAll);

必须要查看第一个集合,这里是一个缺点,但是使用null作为标识值也不是干净的(并且不能与collect一起使用,因为累加器不能返回一个新集合).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读