Limit a stream by a predicate

前端 未结 19 3138
别跟我提以往
别跟我提以往 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:34

    Even I was having a similar requirement -- invoke the web-service, if it fails, retry it 3 times. If it fails even after these many trials, send an email notification. After googling a lot, anyMatch() came as a saviour. My sample code as follows. In the following example, if webServiceCall method returns true in the first iteration itself, stream does not iterate further as we have called anyMatch(). I believe, this is what you are looking for.

    import java.util.stream.IntStream;
    
    import io.netty.util.internal.ThreadLocalRandom;
    
    class TrialStreamMatch {
    
    public static void main(String[] args) {        
        if(!IntStream.range(1,3).anyMatch(integ -> webServiceCall(integ))){
             //Code for sending email notifications
        }
    }
    
    public static boolean webServiceCall(int i){
        //For time being, I have written a code for generating boolean randomly
        //This whole piece needs to be replaced by actual web-service client code
        boolean bool = ThreadLocalRandom.current().nextBoolean();
        System.out.println("Iteration index :: "+i+" bool :: "+bool);
    
        //Return success status -- true or false
        return bool;
    }
    

提交回复
热议问题