Java-8 – intersection of collection flows to new collections

Is there a better and simpler way to solve this problem?

@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) ) );
}

Solution

Reduce is the wrong method because it is not allowed to modify the parameters of the function in this way This is a variable reduction, also known as collection:

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);

The first set must be viewed. This is a disadvantage, but using null as the identification value is not clean (and cannot be used with collect because the accumulator cannot return a new set)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>