Comprehensive Guide to Java 8 Stream API with Practical Examples
This article provides an in-depth tutorial on Java 8 Stream API, covering stream creation, intermediate and terminal operations, filtering, mapping, reduction, collection, sorting, grouping, and practical code examples, helping developers master functional programming with streams in Java.
Java 8 introduced the Stream API and Lambda expressions, enabling concise functional-style operations on collections.
Stream Overview – A Stream represents a sequence of elements supporting intermediate operations (filter, map, flatMap, sorted, etc.) and terminal operations (forEach, collect, reduce, findFirst, anyMatch, etc.). Streams are lazy and do not store data.
Creating Streams – Streams can be created from collections, arrays, or via static methods such as Stream.of() , Stream.iterate() , and Stream.generate() . Example:
List
list = Arrays.asList("a","b","c");
Stream
stream = list.stream();Common Operations – Filtering with filter , mapping with map and flatMap , aggregation with max , min , count , reduction with reduce , and collection with collect(Collectors.toList()) , toSet() , toMap() . Example of filtering salaries above 8000:
List
highEarners = personList.stream()
.filter(p -> p.getSalary() > 8000)
.map(Person::getName)
.collect(Collectors.toList());Statistical Collectors – Using Collectors.counting() , averagingDouble() , summingInt() , and summarizingDouble() to obtain total count, average salary, sum, and summary statistics.
Grouping and Partitioning – partitioningBy splits a stream into two groups based on a predicate, while groupingBy creates multi‑level maps, e.g., grouping employees by gender and region.
Sorting – Streams can be sorted naturally or with a custom Comparator . Example of sorting by salary descending then age descending:
List
sorted = personList.stream()
.sorted((p1,p2) -> {
int cmp = Integer.compare(p2.getSalary(), p1.getSalary());
return cmp != 0 ? cmp : Integer.compare(p2.getAge(), p1.getAge());
})
.map(Person::getName)
.collect(Collectors.toList());Combining Streams – Stream.concat merges streams, distinct removes duplicates, and limit / skip control the number of processed elements.
The article concludes with a brief note on source code reading and an invitation to join related communities.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.