28

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 would be a Guava method to do this, but the closest they come is filter, which doesn't give me the other collection.

I would image the signature of the method would be something like this:

public static <E> Pair<Collection<E>, Collection<E>> partition(Collection<E> source, Predicate<? super E> predicate)

I realize this is super fast to code myself, but I'm looking for an existing library method that does what I want.

4

6 に答える 6

26

グァバを使用Multimaps.index

単語のリストを 2 つの部分に分割する例を次に示します。長さが 3 より大きい部分とそうでない部分です。

List<String> words = Arrays.asList("foo", "bar", "hello", "world");

ImmutableListMultimap<Boolean, String> partitionedMap = Multimaps.index(words, new Function<String, Boolean>(){
    @Override
    public Boolean apply(String input) {
        return input.length() > 3;
    }
});
System.out.println(partitionedMap);

プリント:

false=[foo, bar], true=[hello, world]
于 2012-05-11T08:14:19.550 に答える
4

Eclipse Collections (以前の GS Collections) を使用している場合は、 all でメソッドを使用できpartitionますRichIterables

MutableList<Integer> integers = FastList.newListWith(-3, -2, -1, 0, 1, 2, 3);
PartitionMutableList<Integer> result = integers.partition(IntegerPredicates.isEven());
Assert.assertEquals(FastList.newListWith(-2, 0, 2), result.getSelected());
Assert.assertEquals(FastList.newListWith(-3, -1, 1, 3), result.getRejected());

PartitionMutableListの代わりにカスタム型 を使用する理由はPair、getSelected() および getRejected() の共変の戻り型を許可するためです。たとえば、a をパーティショニングするMutableCollectionと、リストではなく 2 つのコレクションが得られます。

MutableCollection<Integer> integers = ...;
PartitionMutableCollection<Integer> result = integers.partition(IntegerPredicates.isEven());
MutableCollection<Integer> selected = result.getSelected();

コレクションが ではない場合RichIterableでも、Eclipse コレクションで静的ユーティリティを使用できます。

PartitionIterable<Integer> partitionIterable = Iterate.partition(integers, IntegerPredicates.isEven());
PartitionMutableList<Integer> partitionList = ListIterate.partition(integers, IntegerPredicates.isEven());

注:私は Eclipse コレクションのコミッターです。

于 2013-04-15T16:54:47.357 に答える