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.
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);
Count from empty(): 0
Flattened total ignoring the empty one: 3
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