Skip to content
Advertisement

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:

JavaScript

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

Advertisement

Answer

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.

JavaScript

prints:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement