Stream Concat Lazily Merges

Join two streams with Stream.concat, then confirm the result stays lazy by counting side effects before the terminal operation runs.

JavaData Integrity

Code

javasnippet
26 lines
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        AtomicInteger visits = new AtomicInteger();

        Stream<String> first = List.of("a", "b").stream()
                .peek(value -> visits.incrementAndGet());
        Stream<String> second = List.of("c").stream()
                .peek(value -> visits.incrementAndGet());

        // concat is lazy: no element is touched before a terminal operation
        Stream<String> merged = Stream.concat(first, second);
        System.out.println("before terminal: " + visits.get());

        System.out.println("merged: " + merged.toList());
        System.out.println("after terminal: " + visits.get());

        // concat keeps stream order instead of interleaving elements
        System.out.println("flatMap order: " + Stream.of(List.of("x", "y"), List.of("z"))
                .flatMap(List::stream)
                .toList());
    }
}

How the snippet works

The moving parts are the class Main and the function main.

The pipeline is a stream: source, lazy intermediate steps, one terminal collector.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The primary signature is public static void main(String[] args)

Output lines are prefixed (before terminal:, merged:, after terminal:), making each step’s effect easy to spot.

Key statements

Stream<String> first = List.of("a", "b").stream()
.peek(value -> visits.incrementAndGet());
Stream<String> second = List.of("c").stream()
.peek(value -> visits.incrementAndGet());

Interactive Tools for This Topic

FAQ

What does Stream Concat Lazily Merges print when run?
Invoke the file as-is — the `before terminal:`, `merged:`, `after terminal:` prefixes identify which step printed each line.