How to remove items using a stream

Question from Kevin#1322

When you iterate over a map.keySet(), map.values() or map.entrySet() and you call the iterator.remove() method. How does it work that the key-value of the map is removed?

It depends on the exact collection. Sometimes remove won't be implemented, so for most purposes a stream and a filter would be "cleaner" and less prone to running into potentially unsupported methods.

i see

how do you remove items while using a stream?

Like this

List<Integer> xs = List.of(1, 2, 3, 4);
List<Integer> evens = xs.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());

And for a map you would use Collectors.toMap if you need a map at the end. So "filter" is the answer

I see instead of removing you just create a new collection

Yeah, because a bunch of iterators don't support remove (like ArrayList's would, but not what you get from List.of(..)) if you are programming to the List or Map interface instead of a particular implementation it's safer to do a filter.


<- Index