Java Optional filter() and map() Method Examples

1. Introduction

Java's Optional class provides a way to handle the presence or absence of a value without returning null. This can help prevent NullPointerExceptions and make your code more readable and robust. The filter() and map() methods of Optional are powerful tools for conditional actions and transformations.

Key Points

1. Optional is a container object which may or may not contain a non-null value.

2. filter() tests the value within Optional object using a predicate.

3. map() transforms the value inside Optional if it is present.

4. These methods can be chained together to perform complex conditional operations efficiently.

2. Program Steps

1. Import the Optional class.

2. Create an Optional object.

3. Use filter() to perform a conditional check.

4. Use map() to transform the value if present.

5. Display the results.

3. Code Program

import java.util.Optional;

public class OptionalFilterMapExample {

    public static void main(String[] args) {
        // Step 2: Create an Optional object
        Optional<String> optionalValue = Optional.of("Hello World");

        // Step 3: Use filter() to check if the contained string contains "World"
        Optional<String> filteredResult = optionalValue.filter(s -> s.contains("World"));

        // Step 4: Use map() to transform the filtered string to uppercase
        Optional<String> mappedResult =;

        // Print the results
        System.out.println("Filtered Result: " + filteredResult.orElse("No Match"));
        System.out.println("Mapped Result: " + mappedResult.orElse("No Transformations Applied"));


Filtered Result: Hello World
Mapped Result: HELLO WORLD


1. An Optional of a string "Hello World" is created. This Optional is non-empty and contains the string.

2. filter() is used to check if the string inside the Optional contains the substring "World". Since it does, the Optional remains unchanged.

3. map() is then used to transform the string to uppercase. Since the Optional passed the filter condition, the transformation is applied, and the result is "HELLO WORLD".

4. The orElse() method is used for both filter() and map() results to provide default values in case the Optional is empty at any stage of the chain.