HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How to filter a Java Collection (based on predicate)?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howjavafiltercollectionbasedpredicate

Problem

I want to filter a java.util.Collection based on a predicate.

Solution

Java 8 (2014) solves this problem using streams and lambdas in one line of code:

List beerDrinkers = persons.stream()
    .filter(p -> p.getAge() > 16).collect(Collectors.toList());


Here's a tutorial.

Use Collection#removeIf to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):

persons.removeIf(p -> p.getAge() <= 16);


lambdaj allows filtering collections without writing loops or inner classes:

List beerDrinkers = select(persons, having(on(Person.class).getAge(),
    greaterThan(16)));


Can you imagine something more readable?

Disclaimer: I am a contributor on lambdaj

Code Snippets

List<Person> beerDrinkers = persons.stream()
    .filter(p -> p.getAge() > 16).collect(Collectors.toList());
persons.removeIf(p -> p.getAge() <= 16);
List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
    greaterThan(16)));

Context

Stack Overflow Q#122105, score: 864

Revisions (0)

No revisions yet.