Gatherers Scan Running Total
Use Stream gather with Gatherers.scan to emit a running total after every element, including a custom String prefix accumulator.
Code
import java.util.List;
import java.util.stream.Gatherers;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// scan keeps the running state and emits it after every element
List<Integer> totals = IntStream.rangeClosed(1, 6)
.boxed()
.gather(Gatherers.scan(() -> 0, Integer::sum))
.toList();
System.out.println("running totals: " + totals);
// a custom scanner can track a different accumulator type
List<String> paths = List.of("src", "main", "java", "Main.java");
List<String> growing = paths.stream()
.gather(Gatherers.scan(() -> "",
(prefix, part) -> prefix.isEmpty() ? part : prefix + "/" + part))
.toList();
System.out.println("paths: " + growing);
// scan is lazy like every other gatherer
long count = IntStream.range(0, 1000)
.boxed()
.gather(Gatherers.scan(() -> 0, Integer::sum))
.limit(3)
.count();
System.out.println("limited: " + count);
}
}Inside the snippet
The snippet is organized around the class Main and the function main.
The pipeline is a stream: source, lazy intermediate steps, one terminal collector.
What to watch for
- Dependency-free by construction — no registry, no lockfile entry.
Using it
Signature: public static void main(String[] args)
Running the file prints labeled results such as running totals:, paths:, limited: — each operation’s effect is visible in the output.
Key statements
List<String> growing = paths.stream()
.gather(Gatherers.scan(() -> "",
(prefix, part) -> prefix.isEmpty() ? part : prefix + "/" + part))
.toList();
Interactive Tools for This Topic
FAQ
- What does Gatherers Scan Running Total print when run?
- Running the file directly is enough — expect labeled output lines such as `running totals:`, `paths:`, `limited:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.