Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java-8 filter a list without creating a new list

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)

like image 215
Eric Leibenguth Avatar asked Aug 01 '15 09:08

Eric Leibenguth


People also ask

Does stream filter modify the original list?

That means list. stream(). filter(i -> i >= 3); does not change original list. All stream operations are non-interfering (none of them modify the data source), as long as the parameters that you give to them are non-interfering too.

Does filter modify the original array Java?

The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.

How do you filter data in Java?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.

How will you run a filter on a collection?

You can filter Java Collections like List, Set or Map in Java 8 by using the filter() method of the Stream class. You first need to obtain a stream from Collection by calling stream() method and then you can use the filter() method, which takes a Predicate as the only argument.


1 Answers

beerDrinkers.removeIf(p -> p.getAge() <= 16);
like image 70
JB Nizet Avatar answered Sep 23 '22 21:09

JB Nizet