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<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
Stream<String> parallel = list.parallelStream();
Stream<Integer> s = Stream.of(1,2,3);
Stream<Integer> s2 = Stream.iterate(0, x -> x + 3).limit(4);
Stream<Double> 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<Integer> list = Arrays.asList(7,6,9,3,8,2,1);
list.stream().filter(x -> x > 6).forEach(System.out::println);
Optional<Integer> first = list.stream().filter(x -> x > 6).findFirst();
Optional<Integer> any = list.parallelStream().filter(x -> x > 6).findAny();
boolean 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);

Filtering a list of Person objects by salary:

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

3.3 Aggregation

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

3.4 Mapping

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

3.5 Reduction

List<Integer> list = Arrays.asList(1,3,2,8,11,4);
Optional<Integer> 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<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> 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<Integer> 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<Boolean, List<Person>> byHighSalary = personList.stream()
    .collect(Collectors.partitioningBy(p -> p.getSalary() > 8000));
Map<String, List<Person>> bySex = personList.stream()
    .collect(Collectors.groupingBy(Person::getSex));
Map<String, Map<String, List<Person>>> 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<String> bySalary = personList.stream()
    .sorted(Comparator.comparing(Person::getSalary))
    .map(Person::getName)
    .collect(Collectors.toList());
List<String> 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<String> merged = Stream.concat(Stream.of(a1), Stream.of(a2))
    .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());

4. Stream Source Code Analysis

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.