1. Introduction
In Java, a Stream represents a sequence of elements supporting sequential and parallel aggregate operations. The Stream API allows for complex data manipulation using a functional approach. Conversely, a List is a part of the Java Collections Framework and is an ordered collection of elements. Converting a Stream to a List can be useful when we want to store the result of the Stream operations and perform further actions, like indexing or random access.
2. Program Steps
1. Import the necessary libraries.
2. Create a Stream of elements.
3. Convert the Stream to a List using the collect method and Collectors.toList().
4. Display the elements of the List.
3. Code Program
// Step 1: Import the necessary libraries
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamToListExample {
public static void main(String[] args) {
// Step 2: Create a Stream of elements
Stream<String> fruitStream = Stream.of("Apple", "Banana", "Cherry");
// Step 3: Convert the Stream to a List
List<String> fruitList = fruitStream.collect(Collectors.toList());
// Step 4: Display the elements of the List
fruitList.forEach(System.out::println);
}
}
Output:
Apple Banana Cherry
4. Step By Step Explanation
Step 1: Necessary libraries for handling lists, streams, and collectors are imported.
Step 2: A Stream of strings representing fruit names is created using the Stream.of method.
Step 3: The Stream is converted to a List using the collect method along with Collectors.toList(). This results in a new List object, fruitList, which holds all the elements of the original Stream.
Step 4: Each element of the List is printed to the console using the forEach method and method reference System.out::println.