Stream Operations and Transformations on Collections in Java
Java 8 introduced the Stream API, which provides a modern and efficient way to process collections (like List, Set, etc.). Stream operations help to filter, transform, sort, group, and reduce data in a clean and functional style.
Two Types of Stream Operations
| Type | Description |
|---|---|
| Intermediate | Returns a new stream; does not perform processing immediately (lazy). |
| Terminal | Produces a result or a side-effect; triggers the processing of the stream. |
Common Stream Operations
| Operation | Type | Description |
|---|---|---|
filter() |
Intermediate | Selects elements matching a condition |
map() |
Intermediate | Transforms elements |
sorted() |
Intermediate | Sorts elements |
distinct() |
Intermediate | Removes duplicates |
collect() |
Terminal | Collects results into a collection (e.g., List, Set) |
forEach() |
Terminal | Performs an action for each element |
count() |
Terminal | Counts number of elements |
reduce() |
Terminal | Reduces elements to a single result (e.g., sum, min, max) |
iimport java.util.*;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<String> students = Arrays.asList("Anil", "Mahesh", "LotusJavaPrince", "Mahesh", "Datta");
// Stream operations
List<String> processedStudents = students.stream()
.filter(name -> name.length() > 5) // Filter names longer than 5 characters
.map(String::toUpperCase) // Convert to uppercase
.distinct() // Remove duplicates
.sorted() // Sort alphabetically
.collect(Collectors.toList()); // Collect to list
// Output the transformed list
System.out.println("Processed Students:");
processedStudents.forEach(System.out::println);
}
}
/*
LOTUSJAVAPRINCE
MAHESH
*/