Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Library method to partition a collection by a predicate

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.

like image 370
Edward Dale Avatar asked May 11 '12 08:05

Edward Dale


People also ask

How to use partition in Scala?

partition() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns two collections, one collection is of elements which satisfiles a given predicate function and another collection is of elements which do not satisfy the given predicate function.

What is partitioning in Java?

java. In number theory, * a partition of N is a way to write it as a sum of positive integers. * Two sums that differ only in the order of their terms are considered * the same partition.

Can we partition map in Java?

First, we create a result map with two entries, one for each partition. The values are LinkedHashMap s so that insertion order is preserved. Then, we create a HashSet from the list, so that invoking set. contains(k) is a O(1) operation (otherwise, if we did list.

Which return type can be created by partitioningBy collector on stream of string elements?

Collectors.partitioningBy() using a Predicate Each of the elements from the Stream are tested against the predicate, and based on the resulting boolean value, this Collector groups the elements into two sets and returns the result as Map<Boolean, List<T>> .


1 Answers

Use Guava's Multimaps.index.

Here is an example, which partitions a list of words into two parts: those which have length > 3 and those that don't.

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

prints:

false=[foo, bar], true=[hello, world] 
like image 141
dogbane Avatar answered Oct 10 '22 00:10

dogbane