Custom Gatherer Collapses Repeats

A custom Gatherer with ofSequential and Integrator.ofGreedy collapses consecutive repeats, showing state, downstream.push, and the boolean contract.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.stream.Gatherer;
import java.util.stream.Stream;

public class CollapseRepeats {

    // custom Gatherer: collapses consecutive repeats into one
    static Gatherer<String, ?, String> collapseRepeats() {
        class State {
            String previous;
        }
        return Gatherer.<String, State, String>ofSequential(
                State::new,
                Gatherer.Integrator.ofGreedy((state, element, downstream) -> {
                    if (state.previous == null || !state.previous.equals(element)) {
                        state.previous = element;
                        return downstream.push(element);
                    }
                    return true; // 连续重复:吞掉,不下推
                }));
    }

    public static void main(String[] args) {
        List<String> events = List.of("read", "read", "write", "write", "write", "read", "delete");

        List<String> collapsed = events.stream()
                .gather(collapseRepeats())
                .toList();

        System.out.println("raw      : " + events);
        System.out.println("collapsed: " + collapsed);
    }
}

The state object and the greedy integrator

collapseRepeats() builds its Gatherer with Gatherer.ofSequential(State::new, integrator) — sequential because each element must see the previous one’s decision. The local class State holds a single field, String previous. Gatherer.Integrator.ofGreedy((state, element, downstream) -> …) then compares against it: a new value updates state.previous and returns downstream.push(element), while a consecutive repeat takes the return true; path — swallow the element, keep the stream running, push nothing.

What the pipeline prints

raw      : [read, read, write, write, write, read, delete]
collapsed: [read, write, read, delete]

events.stream().gather(collapseRepeats()).toList() runs the source, the gather stage, and the terminal toList() as one pipeline. The triple write collapses to one, the second read after write survives (only consecutive repeats merge), and delete passes through untouched.

The line that decides each element

if (state.previous == null || !state.previous.equals(element)) {
    state.previous = element;
    return downstream.push(element);
}
return true; // 连续重复:吞掉,不下推

downstream.push returning true means the downstream still wants elements; returning that value verbatim is the boolean contract the integrator must honor.

Interactive Tools for This Topic

FAQ

What does Custom Gatherer Collapses Repeats print when run?
Running the file directly is enough — expect labeled output lines such as `raw :`, `collapsed:`.