Limit a stream by a predicate

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

    You can use java8 + rxjava.

    import java.util.stream.IntStream;
    import rx.Observable;
    
    
    // Example 1)
    IntStream intStream  = IntStream.iterate(1, n -> n + 1);
    Observable.from(() -> intStream.iterator())
        .takeWhile(n ->
              {
                    System.out.println(n);
                    return n < 10;
              }
        ).subscribe() ;
    
    
    // Example 2
    IntStream intStream  = IntStream.iterate(1, n -> n + 1);
    Observable.from(() -> intStream.iterator())
        .takeWhile(n -> n < 10)
        .forEach( n -> System.out.println(n));
    

提交回复
热议问题