Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Java 24 Stream Gatherers: 5 New Operations for Complex Data Processing

This article explores Java 24's new Stream Gatherers feature (JEP 485), demonstrating five built-in gatherers—windowFixed, windowSliding, scan, fold, and mapConcurrent—with code examples for batching, sliding windows, cumulative calculations, intermediate aggregation, and bounded concurrent mapping, plus a guide to building custom gatherers for stateful stream transformations.

Introduction

Java 24 introduces a significant new Stream API feature: Gatherers. Initially previewed in JEP 461 and finalized in JEP 485, Gatherers allow developers to define custom intermediate operations, enabling concise implementations for windowing, cumulative calculations, and concurrent processing while preserving lazy, functional stream semantics.

Standard intermediate operations are constrained by cardinality rules: map (1-to-1), filter (1-to-0-or-1), and flatMap (1-to-many). These are stateless and operate per element. Gatherers bridge the gap for stateful, multi-element logic such as fixed-size batching for bulk database inserts, sliding-window moving averages for financial data, element-to-neighbor comparisons, and running totals.

Built-in Gatherers

2.1 windowFixed — Fixed-Size Batching

Gatherers.windowFixed(size)

groups elements into non-overlapping windows of the given size. The last window may be smaller.

List<Integer> storyIds = List.of(50028275, 50029123, 50019911, 50022292, 49997481, 49981264, 50023450);
List<List<Integer>> batches = storyIds.stream().gather(Gatherers.windowFixed(3)).toList();
// Output:
// Batch: [50028275, 50029123, 50019911]
// Batch: [50022292, 49997481, 49981264]
// Batch: [50023450]

Use cases: batch database inserts, paginated chunk processing, batched API requests.

2.2 windowSliding — Overlapping Sliding Windows

Gatherers.windowSliding(size)

produces overlapping windows, advancing one element at a time.

storyIds.stream()
  .limit(10)
  .gather(Gatherers.windowSliding(3))
  .forEach(window -> IO.println("Sliding ID Window: " + window));
// Output:
// Sliding ID Window: [50028275, 50029123, 50019911]
// Sliding ID Window: [50029123, 50019911, 50022292]
// Sliding ID Window: [50019911, 50022292, 49997481]
// Sliding ID Window: [50022292, 49997481, 49981264]
// Sliding ID Window: [49997481, 49981264, 50023450]

Use case: real-time monitoring of commit velocity or detecting sequential ordering anomalies.

2.3 scan — Cumulative Values

Gatherers.scan(initial, function)

emits each intermediate accumulation result, similar to a running total.

List<Integer> transactions = List.of(100, 250, -50, 100);
List<Integer> balanceHistory = transactions.stream()
  .gather(Gatherers.scan(() -> 0, Integer::sum))
  .toList();
// Output: [100, 350, 300, 400]

Use case: lightweight metric tracking such as running account balances.

2.4 fold — Intermediate Aggregation

Gatherers.fold(initial, folder)

folds all elements into a single result and emits only that final value downstream. It operates strictly sequentially.

List<Integer> storyIds = List.of(50028275, 50029123, 50019911, 50022292, 49997481, 49981264, 50023450);
String summaryPayload = storyIds.stream().limit(5)
  .gather(Gatherers.fold(() -> "要闻快照: ", (acc, id) -> acc + "[" + id + "] "))
  .findFirst().orElse("");
// Output: 要闻快照: [50028275] [50029123] [50019911] [50022292] [49997481]

Use case: creating a concise summary string mid-pipeline.

2.5 mapConcurrent — Bounded Parallel Mapping with Virtual Threads

Gatherers.mapConcurrent(maxConcurrency, mapper)

applies the mapping function concurrently using virtual threads (Project Loom), preserving encounter order while limiting concurrency.

List<Integer> storyIds = List.of(39121, 39122, 39123, 39124, 39125);
List<String> titles = storyIds.stream()
  .gather(Gatherers.mapConcurrent(3, id -> fetchStoryTitle(id)))
  .toList();
// fetchStoryTitle simulates a 500 ms network call
// Output shows VirtualThread execution with order preserved

Key properties:

Bounded concurrency (3) : prevents overwhelming downstream services even with thousands of elements.

Virtual threads : blocking I/O does not block platform/OS threads.

Order preservation : output list matches input order despite concurrent execution.

Custom Gatherer: distinctBy

The Gatherer<T, A, R> interface defines four components:

initializer() : creates initial mutable state.

integrator() : processes each input element, updates state, pushes results downstream.

combiner() : merges two states (for parallel execution).

finisher() : optional final operation after stream exhaustion.

Example: a stateful deduplication gatherer keyed by a property extractor, avoiding external collections and preserving laziness.

public static <T, K> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends K> keyExtractor) {
  return Gatherer.ofSequential(
    HashSet::new,
    (state, element, downstream) -> {
      K key = keyExtractor.apply(element);
      if (state.add(key)) {
        downstream.push(element);
      }
      return true;
    }
  );
}

Usage with a News record:

List<News> fetchedStories = List.of(
  new News(1, "Java 27 Released", "pack"),
  new News(2, "Understanding Virtual Threads", "xg"),
  new News(3, "Deep Dive into JEP 485", "pack"), // duplicate author
  new News(4, "Building Modern CLI Apps", "jerry")
);
List<News> uniqueAuthorStories = fetchedStories.stream()
  .gather(HackerNewsGatherers.distinctBy(News::author))
  .toList();
// Output:
// Author: pack -> Title: Java 27 Released
// Author: xg -> Title: Understanding Virtual Threads
// Author: jerry -> Title: Building Modern CLI Apps
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Virtual ThreadsStream APIJava 24Project Loomscanfoldcustom gathererGatherersJEP 485mapConcurrentwindowFixedwindowSliding

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion