-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathGather.java
More file actions
81 lines (72 loc) · 2.31 KB
/
Gather.java
File metadata and controls
81 lines (72 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/
/*
* Copyright (C) 2022 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.stream.operators.flow;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.stream.javadsl.GatherCollector;
import org.apache.pekko.stream.javadsl.Gatherer;
import org.apache.pekko.stream.javadsl.Source;
public class Gather {
static final ActorSystem system = null;
public void zipWithIndex() {
// #zipWithIndex
Source.from(Arrays.asList("A", "B", "C", "D"))
.gather(
() ->
new Gatherer<String, String>() {
private long index = 0L;
@Override
public void apply(String elem, GatherCollector<String> collector) {
collector.push("(" + elem + "," + index + ")");
index += 1;
}
})
.runForeach(System.out::println, system);
// prints
// (A,0)
// (B,1)
// (C,2)
// (D,3)
// #zipWithIndex
}
public void grouped() {
// #grouped
Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
.gather(
() ->
new Gatherer<Integer, String>() {
private final ArrayList<Integer> buffer = new ArrayList<>(3);
@Override
public void apply(Integer elem, GatherCollector<String> collector) {
buffer.add(elem);
if (buffer.size() == 3) {
collector.push(buffer.toString());
buffer.clear();
}
}
@Override
public void onComplete(GatherCollector<String> collector) {
if (!buffer.isEmpty()) {
collector.push(buffer.toString());
}
}
})
.runForeach(System.out::println, system);
// prints
// [1, 2, 3]
// [4, 5, 6]
// [7, 8, 9]
// [10]
// #grouped
}
}