Course contentsShow
← Java
Lesson 1442 of 2,87032. Streams API: Intermediate OperationsFree lesson

Stream.empty() and Conditional Flattening

Returning Stream.empty() from flatMap to conditionally exclude elements during flattening.

Stream.empty() and Conditional Flattening

You'll learn how to use Stream.empty() within flatMap to conditionally exclude elements during the flattening process.

The Core Idea

Sometimes when flattening, you want to include or exclude entire elements based on conditions. Since flatMap expects you to return a Stream from each lambda, you can't simply return null or skip an element. Instead, you return Stream.empty() — a stream with zero elements — which effectively filters out that element during flattening.

Think of it like a postal sorting facility: each package (element) can either explode into multiple items (return a stream with elements) or be discarded entirely (return an empty stream). The empty box contributes nothing to the final conveyor belt.

Practical Usage

List<String> words = List.of("hello", "", "world", "   ", "java");

// Keep only non-blank words, split into characters
List<String> result = words.stream()
    .flatMap(word -> word.isBlank() 
        ? Stream.empty()  // Exclude blank words entirely
        : word.chars().mapToObj(c -> String.valueOf((char) c)))
    .collect(Collectors.toList());
// Result: [h, e, l, l, o, w, o, r, l, d, j, a, v, a]

Here, blank strings are replaced with Stream.empty(), so they contribute no characters to the final result. It's a clean alternative to filtering before or after flatMap.

When to Use This Pattern

  • Conditional flattening based on element properties
  • Avoiding nested filtering operations
  • Cleaner logic when some elements should produce zero outputs

Key Takeaway: Return Stream.empty() from flatMap to conditionally exclude elements during flattening, keeping your pipeline concise and avoiding separate filter steps.