Backend Development 24 min read

Comprehensive Guide to Java 8 Stream API with Practical Examples

This article provides an in‑depth tutorial on Java 8 Stream API, covering its concepts, creation methods, common operations such as filtering, mapping, reducing, collecting, sorting, and grouping, along with numerous runnable code examples that demonstrate how to process collections efficiently using streams.

Top Architect
Top Architect
Top Architect
Comprehensive Guide to Java 8 Stream API with Practical Examples

1. Stream Overview

Java 8 introduced the Stream API together with Lambda expressions, greatly simplifying operations on collections.

Stream treats the source collection as a flow of data, allowing operations like filter, sort, and aggregate.

Stream can be created from arrays or collections and supports two types of operations: intermediate (returning a new stream) and terminal (producing a result).

2. Creating Streams

Streams can be created in three ways:

Using Collection.stream() or Collection.parallelStream() .

Using Arrays.stream(array) for primitive or object arrays.

Using static methods Stream.of() , Stream.iterate() , and Stream.generate() .

List
list = Arrays.asList("a", "b", "c");
Stream
stream = list.stream();
Stream
parallel = list.parallelStream();
Stream
s = Stream.of(1,2,3);
Stream
s2 = Stream.iterate(0, x -> x + 3).limit(4);
Stream
s3 = Stream.generate(Math::random).limit(3);

3. Using Streams

Before using streams, understand the Optional type, which may contain a value or be empty.

3.1 Traversal and Matching

List
list = Arrays.asList(7,6,9,3,8,2,1);
list.stream().filter(x -> x > 6).forEach(System.out::println);
Optional
first = list.stream().filter(x -> x > 6).findFirst();
Optional
any = list.parallelStream().filter(x -> x > 6).findAny();
boolean anyMatch = list.stream().anyMatch(x -> x < 6);

3.2 Filtering

List
list = Arrays.asList(6,7,3,8,1,2,9);
list.stream().filter(x -> x > 7).forEach(System.out::println);

Filtering a list of Person objects by salary:

List
highEarners = personList.stream()
    .filter(p -> p.getSalary() > 8000)
    .map(Person::getName)
    .collect(Collectors.toList());

3.3 Aggregation

List
list = Arrays.asList(1,3,2,8,11,4);
Optional
sum = list.stream().reduce(Integer::sum);
Optional
product = list.stream().reduce((x,y) -> x * y);
Optional
max = list.stream().reduce(Integer::max);

3.4 Mapping

String[] arr = {"abcd","bcdd","defde","fTr"};
List
upper = Arrays.stream(arr)
    .map(String::toUpperCase)
    .collect(Collectors.toList());

3.5 Reduction

List
list = Arrays.asList(1,3,2,8,11,4);
Optional
sum = list.stream().reduce(Integer::sum);

3.6 Collecting

The collect operation gathers stream elements into containers or computes statistics.

3.6.1 Collecting to List/Set/Map

List
evens = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
Set
evenSet = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
Map
map = personList.stream()
    .filter(p -> p.getSalary() > 8000)
    .collect(Collectors.toMap(Person::getName, p -> p));

3.6.2 Statistics

Long count = personList.stream().collect(Collectors.counting());
Double avg = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
Optional
max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
DoubleSummaryStatistics stats = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));

3.6.3 Grouping

Map
> byHighSalary = personList.stream()
    .collect(Collectors.partitioningBy(p -> p.getSalary() > 8000));
Map
> bySex = personList.stream()
    .collect(Collectors.groupingBy(Person::getSex));
Map
>> bySexAndArea = personList.stream()
    .collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));

3.6.4 Joining

String names = personList.stream()
    .map(Person::getName)
    .collect(Collectors.joining(","));
String joined = Arrays.asList("A","B","C").stream()
    .collect(Collectors.joining("-"));

3.6.5 Reducing (Collectors.reducing)

Integer taxedSum = personList.stream()
    .collect(Collectors.reducing(0, Person::getSalary, (i,j) -> i + j - 5000));

3.7 Sorting

List
bySalary = personList.stream()
    .sorted(Comparator.comparing(Person::getSalary))
    .map(Person::getName)
    .collect(Collectors.toList());
List
bySalaryDesc = personList.stream()
    .sorted(Comparator.comparing(Person::getSalary).reversed())
    .map(Person::getName)
    .collect(Collectors.toList());

3.8 Extraction and Combination

String[] a1 = {"a","b","c","d"};
String[] a2 = {"d","e","f","g"};
List
merged = Stream.concat(Stream.of(a1), Stream.of(a2))
    .distinct()
    .collect(Collectors.toList());
List
limited = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
List
skipped = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

4. Stream Source Code Analysis

The source code of the Stream API will be explored in future articles.

JavaData ProcessinglambdaFunctional ProgrammingCollectionsStream APIJava 8
Top Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.