2024-12-04

Java optional

        Optional<String> o;
        o = Optional.empty();
        o.ifPresentOrElse(System.out::println, () -> System.out.println("empty"));
        o.ifPresent(System.out::println);
        //System.out.println(o.get()); //throws error

        o = Optional.ofNullable(null);
        o.ifPresentOrElse(System.out::println, () -> System.out.println("empty"));
        o.ifPresent(System.out::println);
        //System.out.println(o.get()); //throws error

        o = Optional.ofNullable("St");
        o.ifPresentOrElse(System.out::println, () -> System.out.println("empty"));
        o.ifPresent(System.out::println);
        System.out.println(o.get()); //throws error

        //o = Optional.of(null); //throws error

Комментариев нет: