Java Stream How to - Create Optional custom Object value








Question

We would like to know how to create Optional custom Object value.

Answer

/*from w ww . java  2s. co  m*/
import java.util.Optional;

public class Main {

    static class Outer {
        Nested nested;
    }

    static class Nested {
        Inner inner;
    }

    static class Inner {
        String foo;
    }

    public static void main(String[] args) {
        test1();
    }

    private static void test1() {
        Optional.of(new Outer())
            .flatMap(o -> Optional.ofNullable(o.nested))
            .flatMap(n -> Optional.ofNullable(n.inner))
            .flatMap(i -> Optional.ofNullable(i.foo))
            .ifPresent(System.out::println);
    }
}