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

Total Post:24

Points:168
Posted on    August-07-2015 5:29 AM

 Java Java  Collection 
Ratings:


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


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
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:
http://code.google.com/p/lambdaj/  

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