Skip to main content

Java Series #8: Streams & Optional class

Understanding Modern Java: Streams and Null-Safe Code

Published 4 min readMarkdown
Java Series #8: Streams & Optional class

Streams

Java Streams are not data structures.
They don’t store, they don’t modify collections, and they don’t run step-by-step like loops.

A Stream is only a pipeline:
Source → Intermediate Operations → Terminal Operation

Example sources:

  • Collections

  • Arrays

  • File lines

  • IntStream / LongStream / Methods returning streams

How Streams Work

1. Source

Where the data comes from

List<Integer> nums = List.of(1, 2, 3, 4, 5);

2. Intermediate Operations (Lazy)

These do NOT run immediately.
They prepare the pipeline and wait.

Common intermediate functions:

map() – Transform Each Element

Used to convert one type/value into another.

List<Integer> nums = List.of(1, 2, 3);

List<Integer> squares = nums.stream()
        .map(n -> n * n)
        .toList();   // [1,4,9]

filter() – Keep Only Matching Values

Used to remove unwanted elements.

List<Integer> even = nums.stream()
        .filter(n -> n % 2 == 0)
        .toList();   // [2]

peek() – Look Inside Stream (Debugging)

Does not modify values, only inspects.

nums.stream()
    .peek(n -> System.out.println("Value: " + n))
    .toList();

flatMap() – Flatten Nested Data

Converts complex nested structures into a flat stream.

List<List<Integer>> data = List.of(
    List.of(1, 2),
    List.of(3, 4)
);

List<Integer> flat = data.stream()
        .flatMap(list -> list.stream())
        .toList();   // [1,2,3,4]

distinct() – Remove Duplicates

Keeps only unique elements.

List<Integer> unique = List.of(1,2,2,3).stream()
        .distinct()
        .toList();   // [1,2,3]

sorted() – Sort Values

Sorts values in natural or custom order.

List<Integer> sorted = List.of(3,1,2).stream()
        .sorted()
        .toList();   // [1,2,3]

Custom sorting:

List<String> names = List.of("Bob", "Anna", "John");

List<String> sortedDesc = names.stream()
        .sorted((a, b) -> b.compareTo(a))
        .toList();   // [John, Bob, Anna]

3. Terminal Operations (Triggers Execution)

Execution starts only here.

Examples:

  • collect(...)

  • forEach(...)

  • count()

  • findFirst()

  • reduce(...)

  • allMatch()/anyMatch()

This is lazy evaluation:
Streams perform work only when the terminal operation is called.

Stream Example — Filter, Map, Collect

List<String> names = List.of("abhi", "arun", "mani", "sree");

List<String> result =
        names.stream()
             .filter(n -> n.startsWith("a"))   // intermediate
             .map(String::toUpperCase)        // intermediate
             .collect(Collectors.toList());   // terminal

Output:
["ABHI", "ARUN"]

Notice:

  • No extra storage created

  • Functions flow in a pipeline

  • Only collect() triggers execution

Benefits of Streams

  • No storage overhead

  • Cleaner pipelines

  • Lazy: optimized performance

  • Can be parallelized easily

  • Works with huge or infinite sequences

  • Simplifies data transformation

Real-World Use Cases

  • Processing JSON/XML responses

  • Transforming database results

  • Cleaning API responses

  • Mapping inputs to DTOs

  • Concurrent data processing


Optional in Java — A Better Null Handling Approach

Optional is a container that may hold:

  • a value

  • or NO value (empty)

It helps avoid NullPointerException and makes intent clear.

Creating Optional Objects

1. empty()

Optional<String> op = Optional.empty();

2. of(value) — Only if value is NOT null

Optional<String> op = Optional.of("Java");

3. ofNullable(value) — Safe for null

Optional<String> op = Optional.ofNullable(name);

Getting Values

Throws exception if value is null.

2. isPresent()

if(op.isPresent()) { ... }

3. ifPresent(consumer)

op.ifPresent(v -> System.out.println(v));

Providing Default Values

1. orElse(defaultValue)

String name = op.orElse("Guest");

2. orElseGet(supplier)

String name = op.orElseGet(() -> "Default");

3. orElseThrow(exceptionSupplier)

String name = op.orElseThrow(() -> new RuntimeException("Value missing"));

Common Optional Methods

MethodPurpose
empty()Creates empty Optional
of(value)Wraps non-null value
ofNullable(value)Wraps nullable value
get()Returns value or throws error
isPresent()Checks existence
ifPresent(...)Executes if value exists
map(...)Transform value
flatMap(...)Transform and flatten Optional
orElse(default)Default value
orElseGet(supplier)Lazy default
orElseThrow(...)Throws custom exception

Stream + Optional Example (Combined)

List<String> data = List.of("abhi", null, "sari", null, "arun");

List<String> cleaned =
        data.stream()
            .map(s -> Optional.ofNullable(s))       // wrap
            .filter(Optional::isPresent)            // remove nulls
            .map(Optional::get)                     // unwrap
            .collect(Collectors.toList());

Result:
["abhi", "sari", "arun"]

Read about other JAVA8 features from introduction to java8 features

About the author

  • I’m a Full-stack Developer who enjoys turning ideas into simple and useful experiences. I like building clean user interfaces, exploring AI, and understanding how things work behind the scenes. From creating websites to trying out new technologies, I’m always curious and learning something new. Next.js, Node.js, MongoDB, and Java Spring Boot are the tools I use regularly. I enjoy experimenting with projects, sharing what I learn, and improving with every build. Vibing + Thinking.

No comments yet. Be the first to comment.