3.2.1 Stream Creation Explained
Creating streams in Java is a fundamental step in leveraging the power of Java Streams. Streams can be created from various data sources, including collections, arrays, and I/O channels. Understanding how to create streams is essential for performing efficient and concise data processing operations.
Key Concepts
1. Creating Streams from Collections
Streams can be created from any collection that implements the Collection
interface. The stream()
method is used to create a sequential stream, and the parallelStream()
method creates a parallel stream.
Example
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); Stream<String> stream = names.stream(); stream.forEach(System.out::println); // Output: Alice, Bob, Charlie
2. Creating Streams from Arrays
Arrays can be converted into streams using the Arrays.stream()
method. This method is useful when you need to perform stream operations on array elements.
Example
int[] numbers = {1, 2, 3, 4, 5}; IntStream intStream = Arrays.stream(numbers); intStream.forEach(System.out::println); // Output: 1, 2, 3, 4, 5
3. Creating Streams from I/O Channels
Streams can also be created from I/O channels, such as files. The Files.lines()
method reads all lines from a file into a stream, allowing you to process each line as a stream element.
Example
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) { lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); }
Examples and Analogies
Think of creating a stream as setting up a conveyor belt in a factory. The conveyor belt (stream) can be loaded with items (data) from various sources, such as a box (collection), a pallet (array), or a conveyor from another factory (I/O channel). Once the conveyor belt is set up, you can perform various operations on the items as they move along the belt.
By mastering stream creation, you can efficiently process data from diverse sources, making your Java SE 11 applications more flexible and powerful.