Java 8 Stream, getting head and tail

后端 未结 9 2072
太阳男子
太阳男子 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:39

    To get head and tail you need a Lazy Stream implementation. Java 8 stream or RxJava are not suitable.

    You can use for example LazySeq as follows.

    Lazy sequence is always traversed from the beginning using very cheap first/rest decomposition (head() and tail())

    LazySeq implements java.util.List interface, thus can be used in variety of places. Moreover it also implements Java 8 enhancements to collections, namely streams and collectors


    package com.company;
    
    import com.nurkiewicz.lazyseq.LazySeq;
    
    public class Main {
    
        public static void main(String[] args) {
    
            LazySeq ints = integers(2);
            LazySeq primes = sieve(ints);
            primes.take(10).forEach(p -> System.out.println(p));
    
        }
    
        private static LazySeq sieve(LazySeq s) {
            return LazySeq.cons(s.head(), () -> sieve(s.filter(x -> x % s.head() != 0)));
        }
    
        private static LazySeq integers(int from) {
            return LazySeq.cons(from, () -> integers(from + 1));
        }
    
    }
    

提交回复
热议问题