Streams: Stream.empty() is a safe default instead of returning null

Stream.empty() gives a valid, zero-element stream that supports every stream operation, which avoids sprinkling null checks around a method that may have nothing to stream.

Code
List<String> tags = null;
Stream<String> safe = tags == null ? Stream.empty() : tags.stream();
System.out.println("Count from empty(): " + safe.count());
long total = Stream.of(Stream.of("a", "b"), Stream.<String>empty(), Stream.of("c"))
        .flatMap(s -> s)
        .count();
System.out.println("Flattened total ignoring the empty one: " + total);
Output
Count from empty(): 0
Flattened total ignoring the empty one: 3
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms