Simplify Collection Handling with Java 8's Stream API
Java 8 Stream API is a widely adopted 2014 addition that redefines data processing on collections using a declarative, functional programming approach. It offers both sequential and parallel execution modes to efficiently leverage modern multi-core processors, while producing cleaner, more readable code than traditional iterative methods.
A Stream acts as a transient data pipeline that supports operations to filter, transform, sort, or aggregate elements from a source (such as a List or array). Stream operations fall into two primary categories:
- Intermediate operations: These (like
filter,map,sorted) return a new Stream instance, allowing for method chaining. - Terminal operations: These (like
forEach,collect,reduce) finalize the pipeline and generate a non-Stream result (e.g., a value, List, or void).
Code Examples
Creating a Stream
List<String> programmingLanguages = Arrays.asList("Kotlin", "Swift", "Java", "Rust", "Go");
Stream<String> langStream = programmingLanguages.stream();
Filterign and Iteration
programmingLanguages.stream()
.filter(lang -> lang.length() == 4)
.forEach(System.out::println);
Transformation (Mapping)
List<Integer> languageLengths = programmingLanguages.stream()
.map(l -> l.length())
.collect(Collectors.toList());
System.out.println(languageLengths);
Sorting
List<String> sortedLanguages = programmingLanguages.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(sortedLanguages);