--- old/src/java.base/share/classes/java/util/stream/LongStream.java 2016-02-14 20:31:09.279302600 +0600 +++ new/src/java.base/share/classes/java/util/stream/LongStream.java 2016-02-14 20:31:09.050773600 +0600 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -900,6 +900,70 @@ } /** + * Returns a sequential ordered {@code LongStream} produced by iterative + * application of a function {@code f} to an initial element {@code seed}, + * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, + * {@code f(f(seed))}, etc. The stream terminates when {@code predicate} + * returns false. + * + *

The first element (position {@code 0}) in the {@code LongStream} will be + * the provided {@code seed}. For {@code n > 0}, the element at position + * {@code n}, will be the result of applying the function {@code f} to the + * element at position {@code n - 1}. + * + * @param seed the initial element + * @param predicate a predicate to apply to elements to determine when the + * stream must terminate. + * @param f a function to be applied to the previous element to produce + * a new element + * @return a new sequential {@code LongStream} + * @since 9 + */ + public static LongStream iterate(long seed, LongPredicate predicate, LongUnaryOperator f) { + Objects.requireNonNull(f); + Objects.requireNonNull(predicate); + Spliterator.OfLong spliterator = new Spliterators.AbstractLongSpliterator(Long.MAX_VALUE, + Spliterator.ORDERED | Spliterator.IMMUTABLE) { + long prev; + boolean started, finished; + + @Override + public boolean tryAdvance(LongConsumer action) { + Objects.requireNonNull(action); + if (finished) + return false; + long t; + if (started) + t = f.applyAsLong(prev); + else { + t = seed; + started = true; + } + if (!predicate.test(t)) { + finished = true; + return false; + } + action.accept(prev = t); + return true; + } + + @Override + public void forEachRemaining(LongConsumer action) { + Objects.requireNonNull(action); + if (finished) + return; + long t = started ? f.applyAsLong(prev) : seed; + finished = true; + while (predicate.test(t)) { + action.accept(t); + t = f.applyAsLong(t); + } + } + }; + return StreamSupport.longStream(spliterator, false); + } + + /** * Returns an infinite sequential unordered stream where each element is * generated by the provided {@code LongSupplier}. This is suitable for * generating constant streams, streams of random elements, etc.