Upper Knowledge of Java Streams
Upper Knowledge of Java Streams
-By utk
In Java, Streams are a part of the Java Stream API introduced in Java 8. They provide a
modern, functional-style way to process collections of objects. Unlike collections,
Streams don’t store data; they operate on data from a source like a List, Set, or Map,
and perform operations like filtering, mapping, and reducing.
1. Creating Streams
You can create a stream from collections, arrays, or even generate them:
java
CopyEdit
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> nameStream = names.stream();
2. Stream Operations
🔹 Stream Pipelines
A stream pipeline consists of:
Example:
java
CopyEdit
int sum = Arrays.asList(1, 2, 3, 4, 5)
.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * 2)
.sum(); // Output: 12 (2*2 + 4*2)
🔹 Parallel Streams
Streams can be parallelized easily:
java
CopyEdit
list.parallelStream().forEach(System.out::println);