|
| 1 | +import static java.util.stream.Collectors.toList; |
| 2 | +import java.util.LinkedList; |
| 3 | +import java.util.List; |
| 4 | +import java.util.Set; |
| 5 | +import java.util.TreeSet; |
| 6 | +import java.util.stream.Stream; |
| 7 | +import java.util.stream.Gatherer; |
| 8 | +import java.util.stream.Gatherers; |
| 9 | + |
| 10 | +/* |
| 11 | + * To run: `java StreamGatherersExamples.java` |
| 12 | + */ |
| 13 | +public class StreamGatherersExamples { |
| 14 | + public static void main(String[] args) { |
| 15 | + deduplicateStream(); |
| 16 | + filterIfHasAtLeastFiveEvenNumbers(); |
| 17 | + } |
| 18 | + |
| 19 | + static void deduplicateStream() { |
| 20 | + var uniques = Stream.of(1, 2, 5, 8, 1, 9, 3, 5, 4, 8, 7, 3) |
| 21 | + .gather(deduplicate()) |
| 22 | + .collect(toList()); |
| 23 | + System.out.println("Unique elements: " + uniques); |
| 24 | + } |
| 25 | + |
| 26 | + static Gatherer<Integer, Set<Integer>, Integer> deduplicate() { |
| 27 | + return Gatherer.ofSequential( |
| 28 | + // initializer: start the state with a Set |
| 29 | + () -> new TreeSet<>(), |
| 30 | + // integrator: only add if doesn't exists in the set |
| 31 | + Gatherer.Integrator.ofGreedy((state, element, downstream) -> { |
| 32 | + if (state.contains(element)) { |
| 33 | + // ask for the next element if the downstream is on |
| 34 | + return !downstream.isRejecting(); |
| 35 | + } |
| 36 | + state.add(element); |
| 37 | + // pushes downstream and ask for more if the downstream is on |
| 38 | + return downstream.push(element); |
| 39 | + }) |
| 40 | + ); |
| 41 | + } |
| 42 | + |
| 43 | + static void filterIfHasAtLeastFiveEvenNumbers() { |
| 44 | + var list = Stream.generate(() -> (int) (Math.random() * 10) + 1) |
| 45 | + .limit(10) |
| 46 | + .gather(filterAtLeastFiveEvenNumbers()) |
| 47 | + .collect(toList()); |
| 48 | + if (list.isEmpty()) |
| 49 | + System.out.println("There were not enough even numbers"); |
| 50 | + else |
| 51 | + System.out.println("Even numbers: " + list); |
| 52 | + } |
| 53 | + |
| 54 | + static Gatherer<Integer, List<Integer>, Integer> filterAtLeastFiveEvenNumbers() { |
| 55 | + return Gatherer.of( |
| 56 | + // initializer: start a new list |
| 57 | + LinkedList::new, |
| 58 | + // integrator: only add if it is an even number, also increments |
| 59 | + (state, element, downstream) -> { |
| 60 | + if (element % 2 == 0) { |
| 61 | + state.add(element); |
| 62 | + } |
| 63 | + return !downstream.isRejecting(); |
| 64 | + }, |
| 65 | + // combiner: merge the parallel gathering |
| 66 | + (leftState, rightState) -> { |
| 67 | + leftState.addAll(rightState); |
| 68 | + return leftState; |
| 69 | + }, |
| 70 | + // finisher: only pushes if has at least five even numbers |
| 71 | + (state, downstream) -> { |
| 72 | + if (state.size() < 5) { |
| 73 | + return; |
| 74 | + } |
| 75 | + state.forEach(i -> { |
| 76 | + downstream.push(i); |
| 77 | + }); |
| 78 | + } |
| 79 | + ); |
| 80 | + } |
| 81 | +} |
0 commit comments