Add example for foldAsync (#29912)

This commit is contained in:
Nitika Agarwal 2021-01-13 12:31:58 +05:30 committed by GitHub
parent 7920694b81
commit 294661bde1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 75 additions and 4 deletions

View file

@ -341,7 +341,7 @@ class SourceOrFlow {
}
static
// #fold
// #fold // #foldAsync
class Histogram {
final long low;
final long high;
@ -354,6 +354,8 @@ class SourceOrFlow {
// Immutable start value
public static Histogram INSTANCE = new Histogram(0L, 0L);
// #foldAsync
public Histogram add(int number) {
if (number < 100) {
return new Histogram(low + 1L, high);
@ -361,21 +363,44 @@ class SourceOrFlow {
return new Histogram(low, high + 1L);
}
}
// #fold
// #foldAsync
public CompletionStage<Histogram> addAsync(Integer n) {
if (n < 100) {
return CompletableFuture.supplyAsync(() -> new Histogram(low + 1L, high));
} else {
return CompletableFuture.supplyAsync(() -> new Histogram(low, high + 1L));
}
}
// #fold
}
// #fold
// #fold // #foldAsync
void foldExample() {
// #fold
// Folding over the numbers from 1 to 150:
Source.range(1, 150)
.fold(Histogram.INSTANCE, (acc, n) -> acc.add(n))
.fold(Histogram.INSTANCE, Histogram::add)
.runForeach(h -> System.out.println("Histogram(" + h.low + ", " + h.high + ")"), system);
// Prints: Histogram(99, 51)
// #fold
}
void foldAsyncExample() {
// #foldAsync
// Folding over the numbers from 1 to 150:
Source.range(1, 150)
.foldAsync(Histogram.INSTANCE, Histogram::addAsync)
.runForeach(h -> System.out.println("Histogram(" + h.low + ", " + h.high + ")"), system);
// Prints: Histogram(99, 51)
// #foldAsync
}
void takeExample() {
// #take
Source.from(Arrays.asList(1, 2, 3, 4, 5)).take(3).runForeach(System.out::println, system);