How do you use Optional in Java 8 to safely iterate over a list that may be null?

Optional.ofNullable(list) wraps a list that might be null. orElseGet(Collections::emptyList) swaps a null list for an empty one, so you can stream and print it without any null checks or a NullPointerException.

Key Points

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class OptionalList {

    static void printAll(List<String> list) {
        Optional.ofNullable(list)
                .filter(l -> !l.isEmpty())
                .ifPresentOrElse(
                        l -> l.stream().filter(Objects::nonNull).forEach(System.out::println),
                        () -> System.out.println("List is null or empty"));
    }

    public static void main(String[] args) {
        printAll(Arrays.asList("Java", null, "Spring"));
        printAll(Collections.emptyList());
        printAll(null);

        // Java 8 style: no message, just safe iteration
        List<String> notes = null;
        Optional.ofNullable(notes)
                .orElseGet(Collections::emptyList)
                .forEach(System.out::println);
    }
}

Output

Java

Spring

List is null or empty

List is null or empty

Good to Know

ifPresentOrElse() was added in Java 9. In pure Java 8, use isPresent() with an if/else, or the orElseGet() version shown last. Also mention that the best practice is to return an empty list instead of null from methods in the first place.

Interview Tip

A concise interview answer is

I wrap the list in Optional.ofNullable and use orElseGet(Collections::emptyList), so a null list becomes an empty one and I can stream and print it without a NullPointerException. From Java 9, ifPresentOrElse lets me also handle the empty case explicitly.

Last updated: 11 November 2026

Previous question: How do you find duplicate elements and their counts in a list of strings using Java 8?

Next question: Write a program to find the maximum element in an array.

More Stream API Coding Questions - Level II interview questions

All Stream API Coding Questions - Level II questions