Master Java 8 Streams: 20 Real‑World Examples to Boost Your Code

This comprehensive Java 8 Stream tutorial explains how Stream and Lambda simplify collection processing, walks through creating streams, intermediate and terminal operations, and provides twenty practical code examples covering filtering, aggregation, mapping, collecting, grouping, sorting, and parallel execution.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Master Java 8 Streams: 20 Real‑World Examples to Boost Your Code

Java 8 Stream API combined with Lambda expressions can make code shorter and more elegant, yet many developers doubt its readability.

This article demonstrates that Stream is not inherently unreadable by offering numerous practical examples.

Examples include filtering employees with salary >8000, calculating max/average salary, sorting, grouping, and more.

1 Stream Overview

Java 8 introduced Stream and Lambda to simplify collection processing.

Stream treats a collection as a flow of elements that can be filtered, sorted, aggregated, etc., using the Stream API.

Stream operations are divided into intermediate (return a new Stream) and terminal (produce a result).

Intermediate operations can be chained.

Terminal operations end the stream and may produce a collection or a single value.

Key characteristics: lazy evaluation, no data storage, and non‑mutating source.

2 Creating Streams

Streams can be created from collections, arrays, or static methods.

List<String> list = Arrays.asList("a","b","c");
Stream<String> stream = list.stream();          // sequential
Stream<String> parallelStream = list.parallelStream(); // parallel
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 execute operations concurrently when order is not required.

3 Using Streams

Before using streams, understand Optional, a container that may hold null.

Optional provides isPresent() and get() to safely access values.

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();
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);
List<Person> personList = new ArrayList<>();
// add Person objects …
List<String> highEarners = personList.stream()
    .filter(p -> p.getSalary() > 8000)
    .map(Person::getName)
    .collect(Collectors.toList());

3.3 Aggregation (max/min/count)

Optional<String> max = list.stream().max(Comparator.comparing(String::length));
Optional<Integer> maxInt = list.stream().max(Integer::compareTo);

3.4 Mapping (map/flatMap)

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

List<Integer> numbers = Arrays.asList(1,3,5,7,9,11);
List<Integer> plusThree = numbers.stream().map(x -> x + 3).collect(Collectors.toList());

3.5 Reduction (reduce)

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

3.6 Collecting

The collect method gathers stream results into collections, maps, or statistical summaries.

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.1 Statistics

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

3.6.2 Grouping

Map<Boolean, List<Person>> bySalary = 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.3 Joining

String names = personList.stream()
    .map(Person::getName)
    .collect(Collectors.joining(","));

3.7 Sorting

List<String> sortedBySalary = personList.stream()
    .sorted(Comparator.comparing(Person::getSalary).reversed())
    .map(Person::getName)
    .collect(Collectors.toList());

3.8 Combining, Distinct, Limit, Skip

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 ends with a friendly reminder to like the post if it was helpful.

JavaLambdaStream APIJava 8
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

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.