Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit IntStream.iterate to a specific value

I'm generating, let's say, the following range:

IntStream.iterate(1, i -> 3*i)

How do I limit the stream to a specific element value e.g. 100 (not elements count with limit())?

Thank you!

UPDATE the function can be arbitrary

like image 555
Dmitry Senkovich Avatar asked Nov 29 '22 21:11

Dmitry Senkovich


1 Answers

If you can’t use Java 9 yet, you can use the following reimplementation of the three-arg IntStream.iterate:

public static IntStream iterate(int seed, IntPredicate hasNext, IntUnaryOperator next) {
    Objects.requireNonNull(next); Objects.requireNonNull(hasNext);
    return StreamSupport.intStream(
        new Spliterators.AbstractIntSpliterator(
            Long.MAX_VALUE, Spliterator.ORDERED|Spliterator.NONNULL) {
        private IntUnaryOperator op = i -> { op = next; return i; };
        private int value = seed;

        @Override
        public boolean tryAdvance(IntConsumer action) {
            Objects.requireNonNull(action);
            if(op == null) return false;
            int t = op.applyAsInt(value);
            if(!hasNext.test(t)) { op = null; return false; }
            action.accept(value = t);
            return true;
        }

        @Override
        public void forEachRemaining(IntConsumer action) {
            Objects.requireNonNull(action);
            IntUnaryOperator first = op;
            if(first == null) return;
            op = null;
            for(int t = first.applyAsInt(value); hasNext.test(t); t = next.applyAsInt(t))
                action.accept(t);
        }
    }, false);
}

It works similar to Java 9’s IntStream.iterate, except that you have to change the class you’re invoking the static method on (or adapt the import static statement):

iterate(1, i -> i < 100, i -> i*3).forEach(System.out::println);
1
3
9
27
81
like image 160
Holger Avatar answered Dec 04 '22 11:12

Holger