What is the best way to filter a Java collection?

Asked 2 years ago, Updated 2 years ago, 101 views

I want to filter java.util.Collection when implementing.

java filter collections

2022-09-21 17:41

1 Answers

Lambdaj supports filtering of collections without repetition statements or inner classes as follows::

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

Please refer to the following:

https://code.google.com/archive/p/lambdaj/

Update:

With Java 8 (2014) with stream and lambda expression, the above problem can be solved in a single line:

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

See also Tutorial .

If you do not want to modify the data in the collection immediately, you can also use Collection#removeIf:

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


2022-09-21 17:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.