Java Stream concat()

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

In this guide, you will learn about the Stream concat() method in Java programming and how to use it with an example.

1. Stream concat() Method Overview

Definition:

The Stream.concat() method is a static utility method that is used to concatenate two streams into a single stream. The resulting stream will contain elements from both input streams in the order they appear.

Syntax:

static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

Parameters:

- a: the first stream.

- b: the second stream.

Key Points:

- It's a static method and does not operate on a stream instance.

- It is an intermediate operation, meaning the concatenation does not happen immediately. Instead, the operation is executed only when a terminal operation is invoked on the concatenated stream.

- If either stream is parallel, the resulting stream is also parallel.

- Closing the concatenated stream closes both input streams.

- Concatenation is lazy, meaning elements are consumed from the input streams as they are required.

- Care should be taken when using infinite streams with concat, as it can lead to unintended infinite sequences.

2. Stream concat() Method Example

import java.util.stream.Stream;

public class StreamConcatExample {
    public static void main(String[] args) {
        Stream<String> fruitsStream = Stream.of("Apple", "Banana", "Cherry");
        Stream<String> veggiesStream = Stream.of("Artichoke", "Broccoli", "Carrot");

        // Concatenate the two streams
        Stream<String> concatenatedStream = Stream.concat(fruitsStream, veggiesStream);

        // Print the concatenated stream
        concatenatedStream.forEach(System.out::println);
    }
}

Output:

Apple
Banana
Cherry
Artichoke
Broccoli
Carrot

Explanation:

In the provided example: 

We have two streams, one containing fruit names and another containing vegetable names. 

Using Stream.concat(), we concatenate these two streams into a single stream. 

We then print the concatenated stream, which first displays fruits followed by vegetables.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare