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.
🔹 Basic Concepts of Streams
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
Streams support two types of operations:
• Intermediate Operations (return a new stream; lazy)
o .filter()
o .map()
o .sorted()
o .distinct()
o .limit(), .skip()
• Terminal Operations (trigger execution)
o .forEach()
o .collect()
o .reduce()
o .count()
o .anyMatch(), .allMatch(), .noneMatch()
🔹 Example: Filtering and Mapping
java
CopyEdit
List<String> names = Arrays.asList("John", "Jane", "Jack", "Jill");
List<String> filtered = names.stream()
.filter(name -> name.startsWith("J"))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(filtered); // [JOHN, JANE, JACK, JILL]
🔹 Stream Pipelines
A stream pipeline consists of:
1. A source (like a collection)
2. Zero or more intermediate operations
3. A terminal operation
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);