Reputation: 59
Hello I recently started to learn about streams. I'm having a bit of trouble with understanding how to use a stream to remove specific items from an ArrayList.
I know that I can remove specific items using a line like this
nameList.removeIf(e ->(e.getName().equals(c.getName))));
What I'm having trouble with is using code like this to remove items
nameList.stream()
.filter( e -> (e.getName().equals(c.getName())))
.map(nameList::remove);
I'm not exactly sure what I'm missing or am doing wrong with this code. Any help would be appreciated. Thank you.
Upvotes: 0
Views: 124
Reputation: 21124
You may do it like so,
List<Element> removedList = nameList.stream().filter(e -> !e.getName().equals(c.getName()))
.collect(Collectors.toList());
Here's the trick. Rather than removing the elements that matches a given Predicate
from an existing List
you can collect the element that does not match the Predicate
into a different list. This approach complies with the basic concepts of functional programming such as Immutability.
Upvotes: 1
Reputation: 82
The filter function will return a list of the items in the calling stream that match the given predicate function. So if you wanted a list of the items in nameList that the name equals the string “x”, you would do something like:
filteredList = nameList.stream().filter(e -> e.getName().equals(“x”));
You have not included what the variable c is in your example, so I’m not sure how to use that in the example. The map function on top of the filter is not necessary to simply filter elements out of the list.
Upvotes: 0