Understanding Java Stream API: Concepts, Operations, and Practical Examples
This article introduces Java Stream API, explaining its functional programming concepts, lazy evaluation, and parallel processing capabilities, and provides detailed coverage of stream creation, intermediate operations such as filter, map, sorted, limit, and skip, as well as terminal operations like forEach, collect, reduce, match, find, and statistics, complemented by practical code examples.
1. Introduction
Java Stream (Stream) is a sequence of elements that supports functional‑style operations for data transformation and processing. It simplifies code, improves readability, and enables lazy evaluation and parallel execution.
2. Stream Basics
Streams can be created from collections, arrays, Stream.of() , builders, I/O resources, or generator methods such as Stream.generate() and Stream.iterate() . Each stream is single‑use and immutable.
List
numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream
stream = numbers.stream();
Stream
arrayStream = Arrays.stream(new String[]{"Alice","Bob","Carol"});
Stream
generated = Stream.generate(() -> 0);
Stream
iterated = Stream.iterate(0, n -> n + 1);3. Intermediate Operations
Filter retains elements that satisfy a predicate.
Stream
filtered = stream.filter(n -> n % 2 == 0);Map transforms each element.
Stream
mapped = stream.map(n -> n * n);FlatMap flattens nested collections.
Stream
flat = nestedList.stream().flatMap(List::stream);Sorted orders elements, either by natural order or a custom comparator.
Stream
sorted = stream.sorted();
Stream
custom = stream.sorted(Comparator.reverseOrder());Limit keeps the first n elements; skip discards the first n elements.
Stream
limited = stream.limit(3);
Stream
skipped = stream.skip(2);4. Terminal Operations
forEach consumes the stream without returning a result.
stream.forEach(System.out::println);peek allows intermediate inspection while returning a new stream.
stream.peek(System.out::println).collect(Collectors.toList());reduce aggregates elements to a single value.
Optional
sum = stream.reduce((a, b) -> a + b);collect gathers elements into collections or other containers.
List
list = stream.collect(Collectors.toList());
String joined = stream.collect(Collectors.joining(", "));Match operations ( allMatch , anyMatch , noneMatch ) test predicates, while find operations ( findFirst , findAny ) retrieve elements. Statistics methods ( count , max , min ) provide quantitative information.
5. Parallel Streams
Calling parallel() converts a sequential stream into a parallel one, allowing multi‑core processing. Parallel streams are beneficial for large data sets and computationally intensive tasks but require careful handling of thread safety and may not improve performance for small or stateful operations.
numbers.parallelStream()
.map(this::compute)
.forEach(System.out::println);6. Practical Examples
Examples demonstrate filtering strings by length, converting to uppercase, counting elements, using parallel streams, summing integers, and processing files with Files.lines() .
List
result = list.stream()
.filter(s -> s.length() >= 5)
.map(String::toUpperCase)
.collect(Collectors.toList());The article concludes with a call for discussion, community resources, and additional learning material.
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.