T
- Type of object being iterated over.AsyncCloseable
AsyncQueue<T>
, BoundedAsyncQueue<T>
public interface AsyncIterator<T> extends AsyncCloseable
Consider this an async version of Stream
.
AsyncIterators have lazy, pull based, evaluation semantics - values are not computed until they are needed. AsyncIterators are not immutable - like streams, each value they produce is consumed only once. Typically you should not apply multiple transformations to the same source AsyncIterator, it almost certainly won't do what you want it to do.
Implementors of the interface need only implement nextStage()
. Alternatively, the static
methods generate(Supplier)
, supply(Supplier)
, and
unfold(Object, Function)
can be used to create new AsyncIterators from functions that
generate iteration elements.
A note on thread safety: This class makes no assumption that nextStage()
is thread safe!
Many methods that generate transformed iterators assume that nextStage will not be called
concurrently, and even stronger, that nextStage won't be called again until the previous stage
returned by nextStage has completed.
Parallelization may still be accomplished using the partially eager methods described below. The difference is that the parallelization in that case is from producing values in parallel, not consuming values in parallel.
To implement an AsyncIterator you must only implement the nextStage()
method- however,
it is recommended that users avoid actually using nextStage to consume the results of iteration.
It is less expressive and it can also be error prone; it is easy to cause a stack overflow by
incorrectly recursing on calls to nextStage. You should prefer to use the other higher level
methods on this interface.
There are 2 main categories of such methods on this interface: Intermediate and Terminal. These
methods can be combined to form pipelines, which generally consist of a source (often created
with the static constructor methods on this interface (fromIterator(Iterator)
,
unfold(Object, Function)
, etc)), followed by zero or more intermediate operations (such
as filter(Predicate)
, thenApply(Function)
), and completed with a terminal
operation which returns a CompletionStage
(such as forEach(Consumer)
or
fold(Object, BinaryOperator)
). For example, suppose we wanted to accomplish the
following (blocking) procedure:
// request and lookup records one by one until we get 10 relevant records
List<Record> records = new ArrayList<>()
while (records.size() < 10) {
// ask for a record identifier from a remote service (blocking)
RecordId response = requestIdFromIdServer();
// get the actual record from another service (blocking)
Record record = getRecordFromRecordServer(recordIdentifier);
// only add relevant records
if (isRelevant(record)) {
records.add(record);
}
}
If we wanted to do it without doing any blocking, we can use a pipeline and return a
CompletionStage
of the desired record list. Like the blocking version only one request
will be made at a time.
CompletionStage<RecordId> requestIdFromIdServer();
CompletionStage<Record> getRecordFromRecordServer(RecordId recordId);
CompletionStage<List<Response>> responses =
AsyncIterator.generate(this::requestIdFromIdServer) // source iterator
.thenCompose(this::getRecordFromRecordServer) // intermediate transformation
.filter(record -> isRelevant(record)) // intermediate transformation
.take(10) // intermediate transformation
.collect(Collectors.toList()); // terminal operation
Intermediate methods - All methods which return AsyncIterators
are
intermediate methods. They can further be broken down into lazy and partially eager methods.
Methods that end with the suffix ahead are partially eager, the rest are lazy. A lazy
intermediate transformation will not be evaluated until some downstream eager operation is
called. Furthermore, only what is needed to satisfy the eager operation will be evaluated from
the previous iterator in the chain. When only requesting a single element from the transformed
iterator, only a single element may be evaluated from the previous iterator (ex:
thenApply(Function)
), or potentially many elements (ex: filter(Predicate)
).
Methods ending with the suffix ahead , are partially eager. They can be used when there is an expensive transformation step that should be performed in parallel. They will eagerly consume from their upstream iterator up to a specified amount (still sequentially!) and eagerly apply the transformation step.
Intermediate methods will propagate exceptions similarly to CompletionStage
, a dependent
AsyncIterator will return exceptional stages if the upstream iterator generated exceptional
elements.
Terminal methods - Terminal methods consume the iterator and return a
CompletionStage
. After a terminal operation is called, the iterator is considered
consumed and should not be used further. If any of the stages in the chain that comprise
this
iterator were exceptional, the CompletionStage
returned by a terminal
operation will also be exceptional. The exception will short-circuit the terminal operation. For
example, a terminal operation such as forEach(Consumer)
will not to continue to run on
subsequent elements of the iterator and instead immediately complete its returned stage with the
error. Unless otherwise noted, this behavior holds for all terminal methods but may not
documented explicitly.
The exception propagation scheme should be familiar to users of CompletionStage
, upstream
errors will appear wherever the AsyncIterator is consumed and the result is observed (with
CompletableFuture.join()
for instance). Exceptions at any stage in the pipeline can be
recovered from by using exceptionally(Function)
, however this won't recover exceptions
that are produced downstream. A daring user may have applications where they wish to manually
iterate past exceptions without converting them. This can be accomplished by using
nextStage()
directly, see the docs there for more details.
Unless otherwise noted, methods on this interface are free to throw NullPointerException
if any of the provided arguments are null
.
The behavior of an AsyncIterator if nextStage()
is called after the end of iteration
marker is returned is left to the implementation. You may ensure that all subsequent calls always
return the end marker by using fuse()
.
This interface extends AsyncCloseable
, if there are resources associated with
this
iterator that must be relinquished after iteration is complete, the close()
method
should be implemented. Because the majority of methods do not have a manually managed resource, a
default implementation of close which does nothing is provided. Terminal methods on this
interface do not call close()
, it is generally the user's responsibility. The exception
to this rule are for methods that take AsyncIterators or take functions that produce
AsyncIterators, such as concat(AsyncIterator)
or thenFlatten(Function)
, in that
case intermediate iterators will be automatically closed - any such cases will be documented on
the specific method. Similar to the situation with BaseStream.close()
, because the common
case requires no resources the user should only call close if it is possible that the
AsyncIterator
has resources.
Stream
Modifier and Type | Interface | Description |
---|---|---|
static class |
AsyncIterator.End |
A marker enum that indicates there are no elements left in the iterator.
|
Modifier and Type | Method | Description |
---|---|---|
default <A,R> AsyncIterator<R> |
batch(Collector<? super T,A,R> collector,
int batchSize) |
A convenience method provided to invoke
batch(Collector, BiPredicate) with a predicate
that limits batches to a fixed size. |
default <A,R> AsyncIterator<R> |
batch(Collector<? super T,A,R> collector,
BiPredicate<? super A,? super T> shouldAddToBatch) |
Collects the results of this iterator in batches, returning an iterator of those batched
collections.
|
default CompletionStage<Void> |
close() |
Relinquishes any resources associated with this iterator.
|
default <R> CompletionStage<R> |
collect(Supplier<R> supplier,
BiConsumer<R,? super T> accumulator) |
Performs a mutable reduction operation and return a
CompletionStage of the result. |
default <R,A> CompletionStage<R> |
collect(Collector<? super T,A,R> collector) |
Performs a mutable reduction operation using collector and return a CompletionStage of the
result.
|
static <T> AsyncIterator<T> |
concat(AsyncIterator<AsyncIterator<T>> asyncIterators) |
Flattens an AsyncIterator of AsyncIterators into a single AsyncIterator
|
static <T> AsyncIterator<T> |
concat(Iterator<? extends AsyncIterator<T>> asyncIterators) |
Flattens an
Iterator of AsyncIterators into a single AsyncIterator. |
default CompletionStage<Void> |
consume() |
Forces the eager evaluation of the entire iterator, stopping only when
this iterator is
out of elements or an exception is encountered. |
static <T> AsyncIterator<T> |
empty() |
Creates an empty AsyncIterator.
|
static <T> AsyncIterator<T> |
error(Throwable ex) |
Creates an AsyncIterator for which all downstream operations will be completed with an
exception.
|
default AsyncIterator<T> |
exceptionally(Function<Throwable,? extends T> fn) |
Returns an AsyncIterator where any exception produced by
this iterator will be
transformed with the provided function. |
default AsyncIterator<T> |
filter(Predicate<? super T> predicate) |
Transforms the AsyncIterator into one which will only produce results that match
predicate . |
default <U> AsyncIterator<U> |
filterApply(Function<? super T,Optional<U>> fn) |
Applies a transformation and filters this AsyncIterator at the same time.
|
default <U> AsyncIterator<U> |
filterCompose(Function<? super T,? extends CompletionStage<Optional<U>>> fn) |
Composes and filters an AsyncIterator at the same time.
|
default CompletionStage<Optional<T>> |
find(Predicate<? super T> predicate) |
Gets the first element that satisfies predicate, or empty if no such element exists
|
default CompletionStage<T> |
fold(T identity,
BinaryOperator<T> accumulator) |
Sequentially accumulates the elements of type T in this iterator into a single T value.
|
default <U> CompletionStage<U> |
fold(U identity,
BiFunction<U,? super T,U> accumulator) |
Sequentially accumulates the elements of type T in this iterator into a U.
|
default CompletionStage<Void> |
forEach(Consumer<? super T> action) |
Performs the side effecting action until the end of iteration is reached
|
static <T> AsyncIterator<T> |
fromIterator(Iterator<? extends T> iterator) |
Creates an AsyncIterator from an
Iterator |
default AsyncIterator<T> |
fuse() |
Fuses the iterator to the
AsyncIterator.End result after iteration has stopped. |
static <T> AsyncIterator<T> |
generate(Supplier<? extends CompletionStage<T>> supplier) |
Creates an infinite AsyncIterator of type T.
|
static AsyncIterator<Long> |
infiniteRange(long start) |
Creates an infinite AsyncIterator starting at
start . |
CompletionStage<Either<AsyncIterator.End,T>> |
nextStage() |
Returns a stage that will be completed with the next element of
this iterator when it
becomes available, or AsyncIterator.End if there are no more elements. |
static <T> AsyncIterator<T> |
once(T t) |
Creates an AsyncIterator of one element.
|
static AsyncIterator<Long> |
range(long start,
long end) |
Creates an AsyncIterator for a range.
|
static <T> AsyncIterator<T> |
repeat(T t) |
Creates an infinite AsyncIterator of the same value.
|
static <T> AsyncIterator<T> |
supply(Supplier<? extends CompletionStage<Either<AsyncIterator.End,T>>> supplier) |
Creates an AsyncIterator of type T
|
default AsyncIterator<T> |
take(long n) |
Returns an AsyncIterator that will return only the first n elements of
this
AsyncIterator. |
default AsyncIterator<T> |
takeWhile(Predicate<? super T> predicate) |
Returns an AsyncIterator that returns elements from the backing iterator until coming across an
element that does not satisfy the predicate.
|
default <U> AsyncIterator<U> |
thenApply(Function<? super T,? extends U> fn) |
Transforms
this into a new AsyncIterator that iterates over the results of fn
applied to the outcomes of stages in this iterator when they complete normally. |
default <U> AsyncIterator<U> |
thenApplyAsync(Function<? super T,? extends U> fn) |
Transforms
this into a new AsyncIterator that iterates over the results of fn
applied to the outcomes of stages in this iterator when they complete normally. |
default <U> AsyncIterator<U> |
thenApplyAsync(Function<? super T,? extends U> fn,
Executor executor) |
Transforms
this into a new AsyncIterator that iterates over the results of fn
applied to the outcomes of stages in this iterator when they complete normally. |
default <U> AsyncIterator<U> |
thenCompose(Function<? super T,? extends CompletionStage<U>> fn) |
Transforms
this into a new AsyncIterator using the produced stages of fn
applied to the output from the stages of this . |
default <U> AsyncIterator<U> |
thenComposeAhead(Function<? super T,? extends CompletionStage<U>> fn,
int executeAhead) |
Applies a transformation to
this iterator with parallelism. |
default <U> AsyncIterator<U> |
thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn) |
Transforms
this into a new AsyncIterator using the produced stages of fn
applied to the output from the stages of this . |
default <U> AsyncIterator<U> |
thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn,
Executor executor) |
Transforms
this into a new AsyncIterator using the produced stages of fn
applied to the output from the stages of this . |
default <U> AsyncIterator<U> |
thenFlatten(Function<? super T,? extends AsyncIterator<U>> fn) |
Composes fn with the stages of
this iterator to produce new AsyncIterators, and
flattens the resulting iterator of iterators. |
default <U> AsyncIterator<U> |
thenFlattenAhead(Function<? super T,? extends CompletionStage<? extends AsyncIterator<U>>> fn,
int executeAhead) |
Applies a transformation and flattening to
this iterator with parallelism. |
static <T> AsyncIterator<T> |
unfold(T seed,
Function<? super T,? extends CompletionStage<Either<AsyncIterator.End,T>>> f) |
Successively applies the asynchronous function f to the seed until the stage returned by f
contains an empty optional or returns an exception.
|
static <T> AsyncIterator<T> |
unordered(Collection<? extends CompletionStage<T>> stages) |
Creates an AsyncIterator from a collection of
CompletionStages . |
static <T,U,V> AsyncIterator<V> |
zipWith(AsyncIterator<T> tIt,
AsyncIterator<U> uIt,
BiFunction<? super T,? super U,V> fn) |
Creates an iterator that is the result of fn applied to iteration elements returned by tIt and
uI.
|
CompletionStage<Either<AsyncIterator.End,T>> nextStage()
this
iterator when it
becomes available, or AsyncIterator.End
if there are no more elements.
This is not a terminal method, it can be safely called multiple times. However, this method is
not thread safe, and should only be called in a single-threaded fashion. Moreover,
sequential calls should not be made until the CompletionStage
returned by the previous
call has completed. That is to say,
// illegal
pool.execute(() -> nextStage())
pool.execute(() -> nextStage())
// just as illegal
f1 = nextStage();
f2 = nextStage();
// good
nextStage().thenCompose(t -> nextStage());
Though this is not a terminal method, if a terminal method has been called it is no longer safe
to call this method. When nextStage returns AsyncIterator.End
, the iterator has no more elements.
After an iterator emits an AsyncIterator.End
indicator, the result of subsequent calls to nextStage
is undefined.
An AsyncIterator may be capable of producing normally completing stages after having producing
exceptionally completed stages. nextStage is unique in that it can safely continue to be called
even after a returned stage completes exceptionally, whereas all terminal operations short
circuit when encountering an exception. If a user wishes to continue iteration after exception,
they must use nextStage directly, or install exception recovery with
exceptionally(Function)
.
CompletionStage
of the next element for iteration held in the
Either.right()
position, or an instance of AsyncIterator.End
held in the
Either.left()
position indicating the end of iteration.default CompletionStage<Void> close()
This method should be overridden if manual resource management is required, the default
implementation does nothing. This method is not thread safe, and must not be called
concurrently with calls to nextStage()
. This method is not automatically called by
terminal methods, and must be explicitly called after iteration is complete if the underlying
iterator has resources to release. Similar to the situation with BaseStream.close()
,
because the common case requires no resources the user should only call close if it is possible
that the AsyncIterator
has resources. Special care needs to be taken to call close even
in the case of an exception, StageSupport.tryComposeWith(AsyncCloseable, Function)
can
make this more convenient.
class SocketBackedIterator implements AsyncIterator<byte[]> {
...
{@literal @Override}
CompletionStage<Void> close() { return socket.close(); }
}
AsyncCloseable.tryComposeWith(new SocketBackedIterator(socket), socketIt -> socketIt
.thenCompose(this::deserialize)
.filter(this::isRelevantMessage)
.forEach(message -> System.out.println(message)));
Intermediate methods will pass calls to close to their upstream iterators, so it is safe to
call close on an intermediate result of an iterator instead of on it directly. For example,
AsyncIterator<byte[]> original = new SocketBackedIterator(socket);
AsyncIterator<Message> transformed = original.thenCompose(this::deserialize).filter(this::isRelevantMessage);
transformed.close() // will close on original
close
in interface AsyncCloseable
CompletionStage
that completes when all resources associated with this
iterator have been relinquished.default <U> AsyncIterator<U> thenApply(Function<? super T,? extends U> fn)
this
into a new AsyncIterator that iterates over the results of fn
applied to the outcomes of stages in this iterator when they complete normally. When stages in
this
iterator complete exceptionally the returned iterator will emit an exceptional
stage without applying fn
.
intIterator // 1,2,3,...
.thenApply(Integer::toString) //"1","2","3"...
This is a lazy intermediate method.fn
- A function which produces a U from the given Tthis
iteratordefault <U> AsyncIterator<U> thenApplyAsync(Function<? super T,? extends U> fn)
this
into a new AsyncIterator that iterates over the results of fn
applied to the outcomes of stages in this iterator when they complete normally. When stages in
this
iterator complete exceptionally the returned iterator will emit an exceptional
stage without applying fn
. fn
is executed with the previous stage's default
asynchronous execution facility.
intIterator // 1,2,3,...
.thenApplyAsync(Integer::toString) //"1","2","3"...
This is a lazy intermediate method.fn
- A function which produces a U from the given Tthis
iteratordefault <U> AsyncIterator<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
this
into a new AsyncIterator that iterates over the results of fn
applied to the outcomes of stages in this iterator when they complete normally. When stages in
this
iterator complete exceptionally the returned iterator will emit an exceptional
stage without applying fn
. fn
is executed with the provided Executor.
intIterator // 1,2,3,...
.thenApplyAsync(Integer::toString, executor) //"1","2","3"...
This is a lazy intermediate method.fn
- A function which produces a U from the given Texecutor
- a Executor
where the function fn
should runthis
iteratordefault <U> AsyncIterator<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
this
into a new AsyncIterator using the produced stages of fn
applied to the output from the stages of this
. When stages in this
iterator
complete exceptionally the returned iterator will emit an exceptional stage without applying
fn
.
CompletableFuture<String> asyncToString(final int i);
intIterator // 1, 2, 3
.thenCompose(this::asyncToString); //"1", "2", "3"...
This is a lazy intermediate method.fn
- A function which produces a new CompletionStage
from a Tthis
iteratordefault <U> AsyncIterator<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn)
this
into a new AsyncIterator using the produced stages of fn
applied to the output from the stages of this
. When stages in this
iterator
complete exceptionally the returned iterator will emit an exceptional stage without applying
fn
. fn
will be run on the default asynchronous execution facility of the stages
of this
.
CompletableFuture<String> asyncToString(final int i);
intIterator // 1, 2, 3
.thenComposeAsync(this::asyncToString); //"1", "2", "3"...
This is a lazy intermediate method.fn
- A function which produces a new CompletionStage
from a Tthis
iteratordefault <U> AsyncIterator<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn, Executor executor)
this
into a new AsyncIterator using the produced stages of fn
applied to the output from the stages of this
. When stages in this
iterator
complete exceptionally the returned iterator will emit an exceptional stage without applying
fn
. fn
will be run on the supplied executor.
CompletableFuture<String> asyncToString(final int i);
intIterator // 1, 2, 3
.thenComposeAsync(this::asyncToString, executor); //"1", "2", "3"...
This is a lazy intermediate method.fn
- A function which produces a new CompletionStage
from a Texecutor
- a Executor
where the function fn
should runthis
iteratordefault <U> AsyncIterator<U> thenFlatten(Function<? super T,? extends AsyncIterator<U>> fn)
this
iterator to produce new AsyncIterators, and
flattens the resulting iterator of iterators.
Suppose we were making requests for locations with an x coordinate and a y coordinate.
CompletableFuture<Z> lookupCoord(int x, int y);
AsyncIterator<Z> zs = AsyncIterator.range(0, xmax)
.thenFlatten(x -> AsyncIterator.range(0, ymax)
.thenCompose(y -> lookupCoord(x, y)));
// would print z result for (0, 0), (0, 1), (0, 2) ....
zs.forEach(z -> print(z)).toCompletableFuture().join();
Once all elements from an AsyncIterator produced by fn
have been consumed,
close()
is called on that iterator. If close()
produces an exception, an
exceptional stage will be produced in the returned iterator. If close()
exceptions
should be ignored, they should either be squashed in the iterators produced by fn
, or
the consumer may use manual nextStage()
iteration to continue past exceptions on the
returned iterator. It is still necessary to close()
the returned iterator, as the last
AsyncIterator produced by fn
may have only been partially consumed and would not be
closed.
This is a lazy intermediate method.
fn
- A function which produces a new AsyncIteratorfn
to
elements of this
default <U> AsyncIterator<U> thenFlattenAhead(Function<? super T,? extends CompletionStage<? extends AsyncIterator<U>>> fn, int executeAhead)
this
iterator with parallelism. This method
will consume results from this
sequentially, but will apply the mapping function
fn
in parallel. The resulting iterator will retain the order of this
. Up to
executeAhead
asynchronous operations past what the consumer of the new iterator has already
consumed can be started in parallel.
Once all elements from an AsyncIterator produced by fn
have been consumed,
close()
is called on that iterator. If close()
produces an exception, an
exceptional stage will be produced in the handled iterator. If close()
exceptions
should be ignored, they should either be squashed in the input iterators or the consumer may
use manual nextStage()
iteration to continue past exceptions. It is still necessary to
close()
the returned iterator; this will close this
iterator as well as the up
to executeAhead
iterators that have been eagerly produced by fn
. The
CompletionStage
returned from calling close()
on the returned iterator will
not complete until the close completes on all eagerly produced iterators.
This is a partially eager intermediate method.
fn
- A function which produces a CompletionStage
which will complete with an
AsyncIteratorexecuteAhead
- An integer indicating the number of allowable calls to fn
that can
be made ahead of what the user has already consumed from the returned iteratorfn
to
elements of this
thenFlatten(Function)
default <U> AsyncIterator<U> thenComposeAhead(Function<? super T,? extends CompletionStage<U>> fn, int executeAhead)
this
iterator with parallelism. This method will consume
results from this
sequentially, but will apply the mapping function fn
in
parallel. The resulting iterator will retain the order of this
. Up to
executeAhead
asynchronous operations past what the consumer of the new iterator has already
consumed can be started in parallel.
This is a partially eager intermediate method.
fn
- A function which produces a new CompletionStageexecuteAhead
- An integer indicating the number of allowable calls to fn that can be made
ahead of the user has already consumedthenCompose(Function)
default AsyncIterator<T> filter(Predicate<? super T> predicate)
predicate
.
This is a lazy intermediate method.
predicate
- A function that takes a T and returns true if it should be returned by the new
iterator, and false otherwisedefault <U> AsyncIterator<U> filterApply(Function<? super T,Optional<U>> fn)
Optional
cannot hold null values, this method cannot be used to map to an iterator of
possibly null types.
This is a lazy intermediate method.
fn
- a conditional transformation from T
to U
. If fn produces empty, this
result will not be included in the new iteratorU
s that were presentdefault <U> AsyncIterator<U> filterCompose(Function<? super T,? extends CompletionStage<Optional<U>>> fn)
Optional
cannot hold null
values, this method cannot be used to map to an iterator of possibly null types.
This is a lazy intermediate method.
fn
- an asynchronous conditional transformation from T to U. If fn produces empty, this
result will not be included in the new iteratorU
s that were presentdefault AsyncIterator<T> take(long n)
this
AsyncIterator.
This is a lazy intermediate method.
n
- the maximum number of elements to take from this iteratorn
elements or less.default AsyncIterator<T> takeWhile(Predicate<? super T> predicate)
This is a lazy intermediate method.
predicate
- a predicate which returns true
if we can continue returning values
from the iterator, and false otherwise
default AsyncIterator<T> exceptionally(Function<Throwable,? extends T> fn)
this
iterator will be
transformed with the provided function.
This is a lazy intermediate method.
fn
- the Function used to convert an error from this iterator into a T. If fn
itself throws an exception, that exception will be emitted in the resulting iterator.fn
default AsyncIterator<T> fuse()
AsyncIterator.End
result after iteration has stopped. It is normally
undefined behavior to call nextStage()
after AsyncIterator.End
has already been returned. On
a fused iterator, nextStage will just continue to return End.
This is a lazy intermediate method.
nextStage()
after AsyncIterator.End
has already
been returneddefault <A,R> AsyncIterator<R> batch(Collector<? super T,A,R> collector, BiPredicate<? super A,? super T> shouldAddToBatch)
This may be useful for performing bulk operations on many elements, rather than on one element at a time.
This is a lazy intermediate method.
collector
- a Collector
used to collect the elements of this iterator into
individual batches. Each batch will be created by invoking the collector's
Collector.supplier()
methodshouldAddToBatch
- a predicate which determines whether a given element encountered during
iteration should be added to the given (current) batch. If this predicate returns true
for the given element and container, the element will be added
to the container, and the batching operation will continue to draw from the
underlying iterator. If this predicate returns false, the element will not be added and
the current batch will be finished
and returned by the
batching iterator. The element which did not meet the predicate will be tested again by
the next batchCollector
.default <A,R> AsyncIterator<R> batch(Collector<? super T,A,R> collector, int batchSize)
batch(Collector, BiPredicate)
with a predicate
that limits batches to a fixed size.
Each batch will be as large as the given batchSize
except possibly the last one, which
may be smaller due to exhausting the underlying iterator.
This is a lazy intermediate method.
batch(Collector, BiPredicate)
default <U> CompletionStage<U> fold(U identity, BiFunction<U,? super T,U> accumulator)
collect(java.util.stream.Collector<? super T, A, R>)
. For example, to sum the lengths of Strings in an AsyncIterator,
stringIt.fold(0, (acc, s) -> acc + s.length())
.
This is a terminal method.
accumulator
- a function that produces a new accumulation from an existing accumulation
and a new elementidentity
- a starting U valueCompletionStage
containing the resulting U from repeated application of
accumulatordefault CompletionStage<T> fold(T identity, BinaryOperator<T> accumulator)
collect(java.util.stream.Collector<? super T, A, R>)
. For example, to sum an iterator of ints,
intIt.fold(0, (acc,
i) -> acc + i)
.
This is a terminal method.
accumulator
- a function that takes the current accumulated value and a value to fold in
(in that order), and produces a new accumulated value.identity
- a default T valueCompletionStage
containing the resulting T from repeated application of
accumulatordefault CompletionStage<Void> consume()
this
iterator is
out of elements or an exception is encountered.
This is a terminal method.
CompletionStage
that is completed when consumption is finisheddefault <R,A> CompletionStage<R> collect(Collector<? super T,A,R> collector)
This is a terminal method.
A
- The intermediate type of the accumulated objectR
- The final type of the accumulated objectcollector
- a Collector
which will sequentially collect the contents of this
iterator into an R
CompletionStage
which will complete with the collected valueStream.collect(Collector)
default <R> CompletionStage<R> collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator)
CompletionStage
of the result. A
mutable reduction is one where the accumulator has mutable state and additional elements are
incorporated by updating that state.
This is a terminal method.
supplier
- a supplier for a stateful accumulatoraccumulator
- a function which can incorporate T elements into a stateful accumulationCompletionStage
which will complete with the accumulated valueStream.collect(Supplier, BiConsumer, BiConsumer)
default CompletionStage<Void> forEach(Consumer<? super T> action)
This is a terminal method.
action
- a side-effecting action that takes a TCompletionStage
that returns when there are no elements left to apply
action
to, or an exception has been encountered.default CompletionStage<Optional<T>> find(Predicate<? super T> predicate)
This is a terminal method.
predicate
- the predicate that returns true for the desired elementCompletionStage
that completes with the first T to satisfy predicate, or
empty if no such T existsstatic <T> AsyncIterator<T> concat(Iterator<? extends AsyncIterator<T>> asyncIterators)
Iterator
of AsyncIterators into a single AsyncIterator.
// returns an AsyncInterator of 0,1,2,3,4
AsyncIterators.concat(Arrays.asList(
AsyncIterators.range(0, 3),
AsyncIterators.range(3, 5)))
Once all elements from an input AsyncIterator have been consumed, close()
is called on
that iterator. If close()
produces an exception, an exceptional stage will be produced
in the handled iterator. If close()
exceptions should be ignored, they should either
be squashed in the input iterators or the consumer may use manual nextStage()
iteration to continue past exceptions. It is still necessary to close()
the returned
iterator, as the last used AsyncIterator may only be partially consumed.asyncIterators
- an Iterator of AsyncIterators to concatenatestatic <T> AsyncIterator<T> concat(AsyncIterator<AsyncIterator<T>> asyncIterators)
// returns an AsyncIterator of 0,1,2,0,1,2,0,1,2
AsyncIterators.concat(AsyncIterators.generate(() -> AsyncIterators.range(0, 3)).take(3))
Once all elements from an input AsyncIterator have been consumed, close()
is called on
that iterator. If close()
produces an exception, an exceptional stage will be produced
in the returned iterator. If close()
exceptions should be ignored, they should either
be squashed in the input iterators or the consumer may use manual nextStage()
iteration to continue past exceptions. It is still necessary to close()
the returned
iterator; this will close both asyncIterators
as well as the last used AsyncIterator if
it was only partially consumed.asyncIterators
- a AsyncIterator of AsyncIteratorsasyncIterators
static <T,U,V> AsyncIterator<V> zipWith(AsyncIterator<T> tIt, AsyncIterator<U> uIt, BiFunction<? super T,? super U,V> fn)
When the returned iterator is closed
, the stage returned by close will be
complete when both tIt
and uIt
have been closed.
tIt
- an AsyncIterator of TsuIt
- an AsyncIterator of Usfn
- a function that produces a V from a T and a Ustatic <T> AsyncIterator<T> empty()
AsyncIterator.End
markerstatic <T> AsyncIterator<T> fromIterator(Iterator<? extends T> iterator)
Iterator
iterator
- an Iterator
of T elementsiterator
static <T> AsyncIterator<T> once(T t)
t
- the element to returnAsyncIterator.End
marker.static <T> AsyncIterator<T> error(Throwable ex)
ex
- the exception which the CompletionStages
of the returned
iterator will be completed withstatic <T> AsyncIterator<T> repeat(T t)
t
- the value to repeatt
static AsyncIterator<Long> range(long start, long end)
Similar to for(i = start; i < end; i++)
.
The stages returned by nextStage will be already completed.
start
- the start point of iteration (inclusive)end
- the end point of iteration (exclusive)static AsyncIterator<Long> infiniteRange(long start)
start
.start
- the start point of iteration (inclusive)static <T> AsyncIterator<T> unordered(Collection<? extends CompletionStage<T>> stages)
CompletionStages
. When a
stage completes, the value becomes available for consumption in the returned iterator. If a
stage completes exceptionally, the returned iterator will emit an exceptional stage. The order
in which values are returned does not reflect the original order of the collection of stages.stages
- a Collection of CompletionStages
that will be emitted in
the returned iterator as they completestatic <T> AsyncIterator<T> generate(Supplier<? extends CompletionStage<T>> supplier)
supplier
- supplies stages for elements to be yielded by the returned iteratorsupplier
static <T> AsyncIterator<T> supply(Supplier<? extends CompletionStage<Either<AsyncIterator.End,T>>> supplier)
supplier
- produces CompletionStages of elements in the iterator or indicates end of
iteration with AsyncIterator.End
supplier
static <T> AsyncIterator<T> unfold(T seed, Function<? super T,? extends CompletionStage<Either<AsyncIterator.End,T>>> f)
For example, if f = t -> StageSupport.completedStage(Either.right(f(t)))
, then this
would produce an asynchronous stream of the values seed, f(seed), f(f(seed)),
f(f(f(seed))),...
. The iterator is potentially infinite - it would be in the preceding
example.
seed
- the first value produced by the returned iteratorf
- the function that is applied to the previous value to generate the next valueStream.iterate(Object, java.util.function.UnaryOperator)
Copyright © 2018. All rights reserved.