Library method to partition a collection by a predicate

前端 未结 6 675
小鲜肉
小鲜肉 2020-12-29 21:02

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

6条回答
  •  失恋的感觉
    2020-12-29 22:05

    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.

提交回复
热议问题