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.
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.
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.
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.
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>> .
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With