I have a collection of objects that I would like to partition into two collections, one of which passes a predicate and one of which fails a predicate. I was hoping there wo
If you're using Eclipse Collections (formerly GS Collections), you can use the partition
method on all RichIterables
.
MutableList integers = FastList.newListWith(-3, -2, -1, 0, 1, 2, 3);
PartitionMutableList result = integers.partition(IntegerPredicates.isEven());
Assert.assertEquals(FastList.newListWith(-2, 0, 2), result.getSelected());
Assert.assertEquals(FastList.newListWith(-3, -1, 1, 3), result.getRejected());
The reason for using a custom type, PartitionMutableList
, instead of Pair
is to allow covariant return types for getSelected() and getRejected(). For example, partitioning a MutableCollection
gives two collections instead of lists.
MutableCollection integers = ...;
PartitionMutableCollection result = integers.partition(IntegerPredicates.isEven());
MutableCollection selected = result.getSelected();
If your collection isn't a RichIterable
, you can still use the static utility in Eclipse Collections.
PartitionIterable partitionIterable = Iterate.partition(integers, IntegerPredicates.isEven());
PartitionMutableList partitionList = ListIterate.partition(integers, IntegerPredicates.isEven());
Note: I am a committer for Eclipse Collections.