有没有更好、更简单的方法来解决这个问题?
@Test
public void testReduce() {
Set<Integer> foo = ImmutableSet.of(1,2,3,4,8,9);
Set<Integer> bar = ImmutableSet.of(1,3,8,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,3,8) ) );
}
reduce
这是错误的方法,因为不允许您以这种方式修改函数的参数。这是一个可变还原,也称为collect
:
List<Set<Integer>> listOfSets=…;
if (listOfSets.isEmpty()) {
return new HashSet<>();
}
Set<Integer> intersection = listOfSets.stream().skip(1)
.collect(()->new HashSet<>(listOfSets.get(0)), Set::retainAll, Set::retainAll);
必须查看第一组是这里的一个缺点,但是使用null
因为身份值也不干净(并且不能与collect
因为累加器无法返回新的集合)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)