Comprehensive Guide to Java 8 Stream API with Practical Examples
This article provides an in‑depth tutorial on Java 8 Stream API, explaining its concepts, intermediate and terminal operations, and demonstrating over twenty practical code examples—including filtering, mapping, reducing, collecting, grouping, and parallel streams—to help developers master functional-style data processing in Java.
Java 8 introduced the Stream API and Lambda expressions, allowing developers to write concise, functional‑style operations on collections.
Streams treat a source of elements as a pipeline, supporting intermediate operations (filter, map, flatMap, sorted, distinct) that return a new stream, and terminal operations (forEach, collect, reduce, count, max, min) that produce a result or side‑effect.
Key characteristics of streams include non‑storage of data, immutability of the source, and lazy execution—intermediate operations are performed only when a terminal operation is invoked.
Streams can be created from collections, arrays, or static methods such as Stream.of(...) , Arrays.stream(array) , and list.stream() (or list.parallelStream() for parallel execution).
Common examples:
List
list = Arrays.asList(6,7,3,8,1,2,9);
list.stream().filter(x -> x > 7).forEach(System.out::println); // prints 8 9 List
highEarners = personList.stream()
.filter(p -> p.getSalary() > 8000)
.map(Person::getName)
.collect(Collectors.toList()); Optional
longest = strings.stream()
.max(Comparator.comparingInt(String::length));
System.out.println("Longest: " + longest.get());Reduction operations such as reduce can compute sums, products, or custom aggregates, while collect offers a rich set of collectors for converting streams into lists, sets, maps, or statistical summaries.
Grouping and partitioning enable categorising data, e.g., personList.stream().collect(Collectors.groupingBy(Person::getSex)) or partitioningBy(p -> p.getSalary() > 8000) .
Finally, streams support concatenation, distinct, limit, and skip to combine or trim data streams.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.