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

前端 未结 8 1340
不知归路
不知归路 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 14:58

    In one line no, but maybe you could make use of the partitioningBy collector:

    Map> map = 
        set.stream()
           .collect(partitioningBy(Item::qualify, toSet()));
    
    map.get(true).forEach(i -> ((Qualifier)i).operate());
    set = map.get(false);
    

    It might be more efficient as it avoids iterating the set two times, one for filtering the stream and then one for removing corresponding elements.

    Otherwise I think your approach is relatively fine.

提交回复
热议问题