Is it possible to create in Java 8 a unlimitedly growing in lazy way collection, defined by recursion?

前端 未结 3 677
心在旅途
心在旅途 2021-01-05 03:14

I can create a recursive closure:

static IntUnaryOperator fibo;
fibo = 
    (i) -> 
    i<2 ? 1 : fibo.applyAsInt(i-1)+ fibo.applyAsInt(i-2);
         


        
3条回答
  •  时光说笑
    2021-01-05 03:43

    I cannot think up a good general solution, but if you want to access specifically two previous elements, this could be done in quite easy way defining the custom Spliterator like this:

    public static IntStream iterate(int first, int second, IntBinaryOperator generator) {
        Spliterator.OfInt spliterator = new AbstractIntSpliterator(Long.MAX_VALUE, 
                                                 Spliterator.ORDERED) {
            int prev1 = first, prev2 = second;
            int pos = 0;
    
            @Override
            public boolean tryAdvance(IntConsumer action) {
                if(pos < 2) {
                    action.accept(++pos == 1 ? prev1 : prev2);
                } else {
                    int next = generator.applyAsInt(prev1, prev2);
                    prev1 = prev2;
                    prev2 = next;
                    action.accept(next);
                }
                return true;
            }
        };
        return StreamSupport.intStream(spliterator, false);
    }
    

    Usage:

    iterate(1, 1, Integer::sum).limit(20).forEach(System.out::println);
    

提交回复
热议问题