Java 8 Stream, getting head and tail

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

    The solution below does not do state mutations, except for the head/tail deconstruction of the stream.

    The lazyness is obtained using IntStream.iterate. The class Prime is used to keep the generator state

        import java.util.PrimitiveIterator;
        import java.util.stream.IntStream;
        import java.util.stream.Stream;
    
        public class Prime {
            private final IntStream candidates;
            private final int current;
    
            private Prime(int current, IntStream candidates)
            {
                this.current = current;
                this.candidates = candidates;
            }
    
            private Prime next()
            {
                PrimitiveIterator.OfInt it = candidates.filter(n -> n % current != 0).iterator();
    
                int head = it.next();
                IntStream tail = IntStream.generate(it::next);
    
                return new Prime(head, tail);
            }
    
            public static Stream stream() {
                IntStream possiblePrimes = IntStream.iterate(3, i -> i + 1);
    
                return Stream.iterate(new Prime(2, possiblePrimes), Prime::next)
                             .map(p -> p.current);
            }
        }
    

    The usage would be this:

    Stream first10Primes = Prime.stream().limit(10)
    

提交回复
热议问题