Comprehensive Guide to Java 8 Stream API with Practical Examples
This article explains the concepts, creation methods, and extensive usage patterns of Java 8 Stream API—including filtering, mapping, reducing, collecting, sorting, and combining—through detailed code examples that demonstrate how to process collections efficiently with lambda expressions.
Java 8 introduced the Stream API and lambda expressions, enabling concise and expressive operations on collections. This tutorial clarifies common misconceptions about Stream readability and demonstrates how to leverage Streams for real‑world data processing.
1 Stream Overview
The Stream abstraction treats a collection of elements as a pipeline, allowing intermediate operations (e.g., filter, map) that return a new Stream and a single terminal operation that produces a result such as a collection or value.
Stream views the source elements as a flow; the Stream API provides operations like filtering, sorting, and aggregation.
Key characteristics:
Streams do not store data; they compute results on demand.
Original data sources remain unchanged.
Intermediate operations are lazy and execute only when a terminal operation is invoked.
2 Creating Streams
Streams can be created from collections, arrays, or static factory methods:
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
Stream<String> parallelStream = list.parallelStream(); int[] array = {1,3,5,6,8};
IntStream stream = Arrays.stream(array); Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
Stream<Integer> stream2 = Stream.iterate(0, x -> x + 3).limit(4);
Stream<Double> stream3 = Stream.generate(Math::random).limit(3);Parallel streams can be created directly or by invoking parallel() on an existing sequential stream.
3 Using Streams
3.1 Traversal & Matching
List<Integer> list = Arrays.asList(7,6,9,3,8,2,1);
list.stream().filter(x -> x > 6).forEach(System.out::println);
Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
bool anyMatch = list.stream().anyMatch(x -> x < 6);3.2 Filtering
List<Integer> list = Arrays.asList(6,7,3,8,1,2,9);
list.stream().filter(x -> x > 7).forEach(System.out::println);3.3 Aggregation (max/min/count)
List<String> list = Arrays.asList("adnm","admmt","pot","xbangd","weoujgsd");
Optional<String> max = list.stream().max(Comparator.comparing(String::length));3.4 Mapping (map/flatMap)
String[] strArr = {"abcd","bcdd","defde","fTr"};
List<String> upper = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());3.5 Reduction (reduce)
List<Integer> list = Arrays.asList(1,3,2,8,11,4);
Optional<Integer> sum = list.stream().reduce((x,y) -> x + y);
Optional<Integer> product = list.stream().reduce((x,y) -> x * y);3.6 Collecting (collect)
The collect operation gathers stream elements into containers or computes statistics using Collectors utilities.
List<Integer> list = Arrays.asList(1,6,3,4,6,7,9,6,20);
List<Integer> evens = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
Set<Integer> evenSet = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
Map<String, Person> highEarners = personList.stream()
.filter(p -> p.getSalary() > 8000)
.collect(Collectors.toMap(Person::getName, p -> p));3.7 Sorting (sorted)
List<String> sortedBySalary = personList.stream()
.sorted(Comparator.comparing(Person::getSalary).reversed())
.map(Person::getName)
.collect(Collectors.toList());3.8 Extraction & Combination
List<String> merged = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
List<Integer> limited = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
List<Integer> skipped = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());The article concludes with a brief note that deeper source‑code analysis of the Stream implementation will be added later.
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.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.
