Java

Module 5: Stream API – Practical Operations

By Utility Zone · 2026-01-27T18:44:15.510332

Target Audience

  • Java developers who understand Stream basics
  • Developers working with real-world data
  • Anyone using Java 8 in backend applications

1. Objective of This Module

By the end of this module, you will:

  • Use Stream operations to solve real problems
  • Understand commonly used Stream methods
  • Chain operations effectively
  • Avoid common misuse of Streams

2. Commonly Used Stream Operations

filter()

Used to include elements based on a condition.

List<String> result =
    names.stream()
         .filter(name -> name.startsWith("A"))
         .toList();

map()

Transforms each element.

List<Integer> lengths =
    names.stream()
         .map(String::length)
         .toList();

flatMap()

Flattens nested structures.

List<String> allSkills =
    employees.stream()
             .flatMap(emp -> emp.getSkills().stream())
             .toList();

3. Sorting and Removing Duplicates

distinct()

list.stream().distinct().toList();

sorted()

list.stream().sorted().toList();

Custom sorting:

list.stream()
    .sorted(Comparator.comparing(Employee::getSalary))
    .toList();

4. Limiting and Skipping Elements

list.stream().limit(5).toList();
list.stream().skip(5).toList();

Useful for pagination-like scenarios.


5. Chaining Stream Operations

employees.stream()
         .filter(e -> e.getSalary() > 50000)
         .map(Employee::getName)
         .sorted()
         .toList();

✔ Reads like a pipeline
✔ Easy to reason about


6. forEach – Use with Caution

list.stream().forEach(System.out::println);

⚠️ forEach is a terminal operation
⚠️ Avoid using it for business logic
⚠️ Prefer map, collect for transformations


7. Real-World Examples

Example 1: Employee Names by Department

employees.stream()
         .filter(e -> e.getDepartment().equals("IT"))
         .map(Employee::getName)
         .toList();

Example 2: Flatten Nested Lists

orders.stream()
      .flatMap(order -> order.getItems().stream())
      .toList();

8. Common Mistakes

  • Using Streams for simple loops
  • Over-chaining making code unreadable
  • Using forEach for logic
  • Modifying external variables inside streams

9. Hands-On Exercises

Exercise 1

Filter employees earning more than a given salary.

Exercise 2

Convert a list of strings to uppercase using streams.

Exercise 3

Flatten a list of lists using flatMap.


10. Summary

  • Streams shine in data transformation
  • Readability matters more than cleverness
  • Practice real-world use cases

11. What’s Next?

➡️ Module 6: Collectors & Data Aggregation