Java – how to delete objects from the stream in the foreach method?

I have to use arrays: arra and ARRB Arra and ARRB are lists of different types of objects. The add function converts object a to object B. I want to add each object from arra to ARRB and delete the object from arra I try to do this by streaming:

arrA.stream().foreach(c -> {arrB.add(c); arrA.remove(c);});

When I do this, two things happen:

>Not all objects are passed from arra to ARRB. > A null pointer exception is thrown after several iterations

I guess it's because after each remove () call, the length of the array decreases and the iteration counter increases (only the objects under the odd index are passed to ARRB)

Now I can solve this problem by copying the array in one stream call and then deleting the object in the second stream call, but this seems incorrect to me

What is the right solution to this problem?

Edit Additional information: in the actual implementation, this column is not valid if it has been previously filtered

arrA.stream().filter(some condition).foreach(c -> {arrB.add(c); arrA.remove(c);});

Elements with different conditions are added to different lists several times (ARRC, arrd, etc.), but each object can only be in one list

Solution

Streams is intended to be used in a more functional way, and it is best to treat your collection as immutable

The non streaming mode will be:

arrB.addAll(arrA);
arrA.clear();

But you may be using streams, so you can filter the input, so it's more like:

arrB.addAll(arrA.stream().filter(x -> whatever).toList())

Then delete it from arra (thanks @ holgar for your comments)

arrA.removeIf(x -> whatever)

If your predicates are expensive, you can partition:

Map<Boolean,XXX> lists = arrA.stream()
  .collect(Collectors.partitioningBy(x -> whatever));
arrA = lists.get(false);
arrB = lists.get(true);

Or list changes:

List<XXX> toMove = arrA.stream().filter(x->whatever).toList();
arrA.removeAll(toMove);
arrB.addAll(toMove);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>