Can Java 8 Streams operate on an item in a collection, and then remove it?

前端 未结 8 1281
不知归路
不知归路 2020-12-23 14:22

Like just about everyone, I\'m still learning the intricacies (and loving them) of the new Java 8 Streams API. I have a question concerning usage of streams. I\'ll provide a

相关标签:
8条回答
  • 2020-12-23 15:07

    I see Paul's clarity concern when using streams, stated in the top answer. Perhaps adding explaining variable clarifies intentions a little bit.

    set.removeIf(item -> {
      boolean removeItem=item.qualify();
      if (removeItem){
        item.operate();
      }
      return removeItem;
    });
    
    0 讨论(0)
  • 2020-12-23 15:15

    After the operation, they serve no further purpose, and should be removed from the original set. The code works well, but I can't shake the feeling that there's an operation in Stream that could do this for me, in a single line.

    You cannot remove elements from the source of the stream with the stream. From the Javadoc:

    Most stream operations accept parameters that describe user-specified behavior..... To preserve correct behavior, these behavioral parameters:

    • must be non-interfering (they do not modify the stream source); and
    • in most cases must be stateless (their result should not depend on any state that might change during execution of the stream pipeline).
    0 讨论(0)
提交回复
热议问题