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<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream = numbers.stream();
Stream<Integer> arrayStream = Arrays.stream(new String[]{"Alice","Bob","Carol"});
Stream<Integer> generated = Stream.generate(() -> 0);
Stream<Integer> iterated = Stream.iterate(0, n -> n + 1);3. Intermediate Operations
Filter retains elements that satisfy a predicate.
Stream<Integer> filtered = stream.filter(n -> n % 2 == 0);Map transforms each element.
Stream<Integer> mapped = stream.map(n -> n * n);FlatMap flattens nested collections.
Stream<Integer> flat = nestedList.stream().flatMap(List::stream);Sorted orders elements, either by natural order or a custom comparator.
Stream<String> sorted = stream.sorted();
Stream<String> custom = stream.sorted(Comparator.reverseOrder());Limit keeps the first n elements; skip discards the first n elements.
Stream<Integer> limited = stream.limit(3);
Stream<Integer> 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<Integer> sum = stream.reduce((a, b) -> a + b);collect gathers elements into collections or other containers.
List<String> 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<String> 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
