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)
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.
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.
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.
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.
beerDrinkers.removeIf(p -> p.getAge() <= 16);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With