Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)

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

1 Answer

0 votes
by (46k points)

You can solve this problem using stream and lambdaj one-liner codes:

Using Streams:

In all the events, we’ll have to define this condition as a Predicate object:

public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {

    Predicate<Integer> streamsPredicate = item -> item % 2 == 0;

    return baseCollection.stream()

      .filter(streamsPredicate)

      .collect(Collectors.toList());

}

 

Using Lambdaj:

lambdaj allows filtering collections without writing loops or inner classes:

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

    greaterThan(16)));

Happy Learning….!!

Related questions

Browse Categories

...