Created
June 29, 2025 01:52
-
-
Save rokon12/266be60335831732a3fcf5a4e8da81e5 to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - snippet-7.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static <T> Gatherer<T, ?, List<T>> | |
| batchByCondition(Predicate<List<T>> batchComplete) { | |
| return Gatherer.of( | |
| ArrayList::new, // 1️⃣ Current batch being built | |
| (batch, element, downstream) -> { | |
| batch.add(element); // 2️⃣ Add to current batch | |
| if (batchComplete.test(batch)) { // 3️⃣ Check if batch is "full" | |
| downstream.push(new ArrayList<>(batch)); // 4️⃣ Send copy downstream | |
| batch.clear(); // 5️⃣ Start fresh batch | |
| } | |
| return true; // 6️⃣ Keep processing | |
| }, | |
| (batch, downstream) -> { // 7️⃣ Finisher: handle remaining elements | |
| if (!batch.isEmpty()) { | |
| downstream.push(new ArrayList<>(batch)); | |
| } | |
| } | |
| ); | |
| } | |
| List<Integer> numbers = List.of(1, 4, 2, 8, 5, 7, 3, 9, 6); | |
| List<List<Integer>> batches = numbers.stream() | |
| .gather(batchByCondition( | |
| batch -> batch.stream().mapToInt(i -> i).sum() <= 10 // Sum threshold | |
| )) | |
| .toList(); | |
| // Output visualization: | |
| // [1, 4, 2] → Sum: 7 ✓ (7 ≤ 10, continue) | |
| // [1, 4, 2, 8] → Sum: 15 ✗ (15 > 10, emit [1,4,2], start new with [8]) | |
| // [8] → Sum: 8 ✓ (8 ≤ 10, continue) | |
| // [8, 5] → Sum: 13 ✗ (13 > 10, emit [8], start new with [5]) | |
| // ... and so on |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment