Home > DeveloperSection > Forums > What is the best way to filter a Java Collection?
Felix Pickles
Felix Pickles

Total Post:24

Posted on    August-07-2015 5:29 AM

 Java Java  Collection 

 1 Reply(s)
 655  View(s)
Rate this:
I want to filter a java.util.Collection based on a predicate.

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    August-07-2015 6:17 AM

lambdaj allows to filter collections without writing loops or inner classes as in the following example:

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

Can you imagine something more readable? You can find it here:

With Java 8 update (2014) comes streams and lambdas, solving this problem with a simple one-liner:

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

Modified On Aug-07-2015 06:19:23 AM

Don't want to miss updates? Please click the below button!

Follow MindStick