Java Stream empty() Example

1. Introduction

This tutorial explores the empty() method of the Java Stream API. Stream.empty() is used to create an empty stream. This method is particularly useful when you need a stream with no elements, often used in scenarios requiring a default or fallback stream.

Key Points

1. Stream.empty() creates an empty stream.

2. It is useful when you need to return a stream that should not contain any elements, typically in conditional operations or as a default value.

3. An empty stream is often used in conjunction with methods like concat() to ensure operations do not fail when one of the streams has no elements.

2. Program Steps

1. Create an empty Stream.

2. Attempt to process or collect elements from the empty Stream.

3. Optionally, use the empty Stream in concatenation with another Stream.

3. Code Program

import java.util.List;

public class StreamEmptyExample {

    public static void main(String[] args) {
        // Creating an empty Stream
        Stream<String> emptyStream = Stream.empty();

        // Collecting elements from the empty Stream
        List<String> listFromEmpty = emptyStream.collect(Collectors.toList());
        System.out.println("List from empty stream: " + listFromEmpty);

        // Using empty Stream in concatenation
        Stream<String> activeStream = Stream.of("Java", "Stream");
        Stream<String> concatenatedStream = Stream.concat(emptyStream, activeStream);
        List<String> result = concatenatedStream.collect(Collectors.toList());
        System.out.println("Concatenated result: " + result);


List from empty stream: []
Concatenated result: [Java, Stream]


1. Stream.empty() creates an empty stream, which contains no elements.

2. emptyStream.collect(Collectors.toList()) collects elements from the empty stream into a list, resulting in an empty list because the stream has no elements.

3. Stream.of("Java", "Stream") creates a stream with elements "Java" and "Stream".

4. Stream.concat(emptyStream, activeStream) demonstrates concatenating an empty stream with a non-empty stream. Note, as the emptyStream was already consumed, it effectively contributes nothing, and only elements from activeStream appear in the result.

5. concatenatedStream.collect(Collectors.toList()) collects the results of the concatenation into a list, showing that the concatenated stream only includes elements from the non-empty stream.