【发布时间】:2016-07-08 12:07:57
【问题描述】:
有没有更好、更简单的方法来解决这个问题?
@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) ) );
}
【问题讨论】:
-
您可以简单地使用
ImmutableList.of(foo,bar).stream()而不是Stream.of(foo,bar)... -
@Wilson:我看到了这个问题。我需要一个小溪交叉口,而不仅仅是两组
-
@Holger:谢谢。这只是一个示例代码。在实际代码中,我希望将一组集合作为输入
标签: java-8 java-stream