Limit a stream by a predicate

前端 未结 19 3065
别跟我提以往
别跟我提以往 2020-11-21 22:54

Is there a Java 8 stream operation that limits a (potentially infinite) Stream until the first element fails to match a predicate?

In Java 9 we can use

19条回答
  •  既然无缘
    2020-11-21 23:41

    You can't abort a stream except by a short-circuiting terminal operation, which would leave some stream values unprocessed regardless of their value. But if you just want to avoid operations on a stream you can add a transform and filter to the stream:

    import java.util.Objects;
    
    class ThingProcessor
    {
        static Thing returnNullOnCondition(Thing thing)
        {    return( (*** is condition met ***)? null : thing);    }
    
        void processThings(Collection thingsCollection)
        {
            thingsCollection.stream()
            *** regular stream processing ***
            .map(ThingProcessor::returnNullOnCondition)
            .filter(Objects::nonNull)
            *** continue stream processing ***
        }
    } // class ThingProcessor
    

    That transforms the stream of things to nulls when the things meet some condition, then filters out nulls. If you're willing to indulge in side effects, you could set the condition value to true once some thing is encountered, so all subsequent things are filtered out regardless of their value. But even if not you can save a lot of (if not quite all) processing by filtering values out of the stream that you don't want to process.

提交回复
热议问题