Master Java 8 Stream API: 20 Real‑World Examples and Hands‑On Code

This tutorial introduces Java 8 Stream and Lambda, explains stream concepts, intermediate and terminal operations, and demonstrates 20 practical code examples covering filtering, mapping, reducing, collecting, grouping, sorting, and parallel processing to help developers efficiently manipulate collections.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Master Java 8 Stream API: 20 Real‑World Examples and Hands‑On Code

What Is Stream?

Stream treats a collection of elements as a flow, allowing operations such as filtering, sorting, and aggregation via the Stream API.

Streams can be created from collections or arrays, and operations are divided into intermediate (returning a new stream) and terminal (producing a result) stages.

Creating Streams

From a collection: list.stream() or list.parallelStream() From an array: Arrays.stream(array) Static methods: Stream.of(), Stream.iterate(),

Stream.generate()
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);

Intermediate Operations

filter : keep elements that match a predicate.

map : transform each element.

flatMap : flatten streams of streams.

sorted : sort elements (natural or with a comparator).

Example: Filter Employees with Salary > 8000

List<Person> personList = new ArrayList<>();
// add Person objects …
List<String> highEarners = personList.stream()
    .filter(p -> p.getSalary() > 8000)
    .map(Person::getName)
    .collect(Collectors.toList());
System.out.println("High earners: " + highEarners);

Example: Convert Strings to Uppercase and Add 3 to Integers

String[] strArr = {"abcd", "bcdd", "defde", "fTr"};
List<String> upper = Arrays.stream(strArr)
    .map(String::toUpperCase)
    .collect(Collectors.toList());
List<Integer> intList = Arrays.asList(1,3,5,7,9,11);
List<Integer> plusThree = intList.stream()
    .map(x -> x + 3)
    .collect(Collectors.toList());

Terminal Operations

forEach : iterate and perform an action.

findFirst / findAny : retrieve an element.

anyMatch / allMatch / noneMatch : test predicates.

count : count elements.

max / min : find extreme values.

reduce : aggregate to a single value.

Example: Find First Value Greater Than 6

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();
System.out.println("First match: " + first.get());

Collecting Results

The collect method gathers stream elements into collections or other data structures using Collectors. toList(), toSet(),

toMap()
counting()

, averagingInt(),

summingInt()
groupingBy()

,

partitioningBy()
joining()

to concatenate strings.

Example: Group Employees by Gender and Region

Map<String, List<Person>> byGender = personList.stream()
    .collect(Collectors.groupingBy(Person::getSex));
Map<String, Map<String, List<Person>>> byGenderAndArea = personList.stream()
    .collect(Collectors.groupingBy(Person::getSex,
        Collectors.groupingBy(Person::getArea)));

Example: Summarize Salary 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));

Sorting

Streams can be sorted naturally or with a custom comparator.

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

Combining and Slicing Streams

Use Stream.concat, distinct, limit, and skip for merging and sub‑setting.

List<String> merged = Stream.concat(Stream.of("a","b"), Stream.of("b","c"))
    .distinct()
    .collect(Collectors.toList());
List<Integer> firstTen = Stream.iterate(1, x -> x + 2)
    .limit(10)
    .collect(Collectors.toList());
List<Integer> skipOne = Stream.iterate(1, x -> x + 2)
    .skip(1)
    .limit(5)
    .collect(Collectors.toList());

Employee Class Used in Examples

class Person {
  private String name;
  private int salary;
  private int age;
  private String sex;
  private String area;
  public Person(String name, int salary, int age, String sex, String area) {
    this.name = name;
    this.salary = salary;
    this.age = age;
    this.sex = sex;
    this.area = area;
  }
  // getters and setters omitted for brevity
}

By working through these 20 examples, readers can master the Stream API, write concise functional code, and improve performance, especially when processing large data sets with parallel streams.

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.

JavaLambdafunctional programmingCollectionsStream API
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

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.