Java 8 Stream, getting head and tail

后端 未结 9 2079
太阳男子
太阳男子 2020-11-30 05:40

Java 8 introduced a Stream class that resembles Scala\'s Stream, a powerful lazy construct using which it is possible to do something like this very concisely:



        
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 06:28

    Here is another recipe using the way suggested by Holger. It use RxJava just to add the possibility to use the take(int) method and many others.

    package com.company;
    
    import rx.Observable;
    
    import java.util.function.IntPredicate;
    import java.util.stream.IntStream;
    
    public class Main {
    
        public static void main(String[] args) {
    
            final IntPredicate[] p={(x)->true};
            IntStream primesStream=IntStream.iterate(2,n->n+1).filter(i -> p[0].test(i)).peek(i->p[0]=p[0].and(v->v%i!=0)   );
    
            Observable primes = Observable.from(()->primesStream.iterator());
    
            primes.take(10).forEach((x) -> System.out.println(x.toString()));
    
    
        }
    
    }
    

提交回复
热议问题