java-8 filter a list without creating a new list

2019-03-18 05:27发布

问题:

I'm looking for the cleanest way to filter a list in Java-8, with a simple lambda Predicate, without creating a new list.

In particular, this solution is not suitable, as toList() returns a new List:

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

Note that the following solution does not work either, because the list should be clear()ed of its original values (but obviously, if you clear it before filtering, there's nothing left to filter...):

persons.stream()
    .filter(p -> p.getAge() > 16)
    .forEach((p) -> persons.add(p));

(Also, I'd prefer a solution not involving the use of a 3rd party library or framework)

回答1:

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