Tag: Optional

Understanding java jdk8 Optional

        System.out.println( Optional.empty() ); // Optional.empty
        System.out.println( Optional.ofNullable(null) ); // Optional.empty
        System.out.println( Optional.ofNullable("a") ); // Optional[a]
        System.out.println( Optional.ofNullable("a").get() ); // a


        System.out.println( Optional.ofNullable("a").filter(s -> true) ); // Optional[a] (filter match)
        System.out.println( Optional.ofNullable("a").filter(s -> false) ); // Optional.empty (filter not match)

        System.out.println( Optional.ofNullable("a").map(s -> null)); // Optional.empty (mapper function returning null)
        System.out.println( Optional.ofNullable("a").map(s -> "b")); // Optional[b] (re-map)
        System.out.println( Optional.ofNullable("a").map(s -> "b".equals(s) ? s : null) ); // Optional.empty (filtering using map)
        System.out.println( Optional.ofNullable("a").map(s -> Optional.of("b")) ); // Optional[Optional[b]] (mapper function returning optional)
        System.out.println( Optional.empty().map(s -> { System.out.print("map"); return "b"; }) ); // Optional.empty (mapper not run)

        System.out.println( Optional.ofNullable("a").flatMap(s -> Optional.of("b")) ); // Optional[b] (mapper function returning optional)

        System.out.println( Optional.of("a").orElse("c") ); // a
        System.out.println( Optional.empty().orElse("c") ); // c


        System.out.println( Optional.ofNullable(null)
                .map(s -> printAndReturn("map: ", "b"))
                .orElse(printAndReturn("orElse: ", "c")) ); // orElse: c (executed only orElse branch, returned value c)

        System.out.println( Optional.of("a")
                                    .map(s -> printAndReturn("map: ", "b"))
                                    .orElse(printAndReturn("orElse: ", "c")) ); // map: orElse: b (executed both branches, returned value b)

        System.out.println( Optional.of("a")
                .map(s -> printAndReturn("map: ", "b"))
                .orElseGet(() -> printAndReturn("orElse: ", "c")) ); // map: b (executed only map branch, returned value b)