Convert Stream to List in Java

1. Introduction

Converting a Stream to a List in Java is a common operation, especially when working with the Java Stream API for processing collections or arrays of data. Streams provide a high-level abstraction for Java collection operations, allowing for expressive and efficient data processing. After processing data with a Stream, you may often need to collect the results into a List for further use. This blog post will demonstrate how to convert a Stream to a List in Java using the Collectors utility.

2. Program Steps

1. Create a Stream of elements.

2. Use the collect method along with Collectors.toList() to convert the Stream to a List.

3. Display the resulting List.

3. Code Program

import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;

public class StreamToList {
    public static void main(String[] args) {
        // Step 1: Creating a Stream of elements
        Stream<String> stream = Stream.of("Apple", "Banana", "Cherry", "Date");

        // Step 2: Converting Stream to List
        List<String> list = stream.collect(Collectors.toList());

        // Step 3: Displaying the resulting List
        System.out.println("List from Stream: " + list);
    }
}

Output:

List from Stream: [Apple, Banana, Cherry, Date]

Explanation:

1. The program begins by creating a Stream of strings using Stream.of(), which creates a stream from a sequence of object references.

2. To convert the Stream to a List, the collect method of the Stream is used. This method takes a Collector that accumulates input elements into a new List. Collectors.toList() is provided as the argument to collect, which acts as the necessary Collector for accumulating the elements of the stream into a List.

3. The resulting List, which contains all the elements from the original Stream, is stored in the variable list.

4. Finally, the content of the list is printed to the console, showing that the Stream has been successfully converted into a List containing all the original elements in the order they were in the Stream.

5. This example demonstrates the straightforward process of converting a Stream to a List in Java, utilizing the Collectors utility class to easily collect stream elements into various types of collections.

Comments