The methods addAll
, retainAll
and removeAll
are the methods most commonly used to implement union
, intersect
and difference
in Java. With Streams in Java 8+, you do have some more options for intersect
and difference
using filter
as pointed out in a previous answer.
If you're open to using a third-party library, the following code will work with primitive collections using Eclipse Collections when version 11.0 of the library is released.
@Test
public void unionIntersectDifferenceReverse()
{
IntList list1 = IntLists.immutable.with(0, 2, 4, 5, 6, 8, 10);
IntList list2 = IntLists.immutable.with(5, 6, 7, 8, 9, 10);
MutableIntSet set1 = list1.toSet();
MutableIntSet set2 = list2.toSet();
IntSet union = set1.union(set2);
IntSet intersection = set1.intersect(set2);
IntSet difference = set1.difference(set2);
IntList reversed = list1.toReversed();
Assert.assertEquals(IntSets.mutable.with(0, 2, 4, 5, 6, 7, 8, 9, 10), union);
Assert.assertEquals(IntSets.mutable.with(5, 6, 8, 10), intersection);
Assert.assertEquals(IntSets.mutable.with(0, 2, 4), difference);
Assert.assertEquals(IntLists.mutable.with(10, 8, 6, 5, 4, 2, 0), reversed);
}
This functionality was recently contributed to primitive Sets in Eclipse Collections. The linked blog describes how these methods are implemented on primitive sets.
The following code uses object collections with boxed Integers. This code will work with Eclipse Collections releases available today.
@Test
public void unionIntersectDifferenceReverseWithBoxedIntegers()
{
ImmutableList<Integer> list1 = Lists.immutable.with(0, 2, 4, 5, 6, 8, 10);
ImmutableList<Integer> list2 = Lists.immutable.with(5, 6, 7, 8, 9, 10);
MutableSet<Integer> set1 = list1.toSet();
MutableSet<Integer> set2 = list2.toSet();
MutableSet<Integer> union = set1.union(set2);
MutableSet<Integer> intersection = set1.intersect(set2);
MutableSet<Integer> difference = set1.difference(set2);
ImmutableList reversed = list1.toReversed();
Assert.assertEquals(Sets.mutable.with(0, 2, 4, 5, 6, 7, 8, 9, 10), union);
Assert.assertEquals(Sets.mutable.with(5, 6, 8, 10), intersection);
Assert.assertEquals(Sets.mutable.with(0, 2, 4), difference);
Assert.assertEquals(Lists.mutable.with(10, 8, 6, 5, 4, 2, 0), reversed);
}
Note: I am a committer for Eclipse Collections.