How do I use map() method of Optional object?

The map method of the Optional class in Java is used to transform the value contained in the Optional. map allows you to apply a function on the value inside the Optional and returns an Optional that contains the result of the function.

Here is an example of how to use it:

package org.kodejava.util;

import java.util.Optional;

public class OptionalMapExample {
    public static void main(String[] args) {

        // Create an Optional<String>
        Optional<String> optional = Optional.of("Hello");

        // Use map method to transform the contained value
        Optional<Integer> transformedOptional = optional.map(String::length);

        // Use ifPresent to print the result if the Optional is not empty
        transformedOptional.ifPresent(System.out::println);
    }
}

In this example, we start with an Optional<String> that contains the string “Hello”. We then use map to apply the String::length method on the contained string. This transforms the Optional<String> into an Optional<Integer>, where the integer is the length of the string.

Lastly, we use ifPresent to print the result. In this case, the integer 5 will be printed.

Here is another example, where map helps us to handle null values:

Optional<String> optional = Optional.ofNullable(null);

// If optional is not present, it will print "0"
System.out.println(optional.map(String::length).orElse(0));

In this case, trying to apply String::length on a null value would result in a NullPointerException. However, using map in combination with Optional, allows us to safely transform the value and even provide a default result (“0” in this case) if the Optional is empty. This makes handling null values more reliable and your code less error-prone.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.