0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

c is just an object that is similar to the objects stored in e. What I wanted to do was to filter out objects that were the same to c (like same name, hence using .getName() ) and then remove them from the ArrayList. I was wondering if it was possible to do that, to filter and also call the ArrayList function 'remove' to take out any objects after it was filtered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.