how to remove object from stream in foreach method?
Streams are designed to be used in a more functional way, preferably treating your collections as immutable.
The non-streams way would be:
arrB.addAll(arrA);arrA.clear();
However you might be using Streams so you can filter the input so it's more like:
arrB.addAll(arrA.stream().filter(x -> whatever).toList())
then remove from arrA (thanks to @Holgar for the comment).
arrA.removeIf(x -> whatever)
If your predicate is expensive, then you could partition:
Map<Boolean, XXX> lists = arrA.stream() .collect(Collectors.partitioningBy(x -> whatever));arrA = lists.get(false);arrB = lists.get(true);
or make a list of the changes:
List<XXX> toMove = arrA.stream().filter(x->whatever).toList();arrA.removeAll(toMove);arrB.addAll(toMove);
As the others have mentioned, this is not possible with foreach
- as it is impossible with the for (A a: arrA)
loop to remove elements.
In my opinion, the cleanest solution is to use a plain for while
with iterators - iterators allow you to remove elements while iterating (as long as the collection supports that).
Iterator<A> it = arrA.iterator()while (it.hasNext()) { A a = it.next(); if (!check(a)) continue; arrB.add(a); it.remove();}
This also saves you from copying/cloning arrA
.