Java 8 Optional. Why of and ofNullable?

后端 未结 8 1518
旧时难觅i
旧时难觅i 2021-02-07 01:01

I have a question regarding Java 8\'s Optional, the purpose of which is to tackle NullPointerException exceptions.

The question is, what is the reason for h

相关标签:
8条回答
  • 2021-02-07 01:56

    Code example: Optional.of() VS Optional.ofNullable()

    @Test
    public void TestOptional() {
    
        String message = "Hello World!";
        System.out.println("message -> " + message + "\n");
    
        Optional<String> genderOptional = Optional.of(message);
        System.out.println("Optional.of(message) -> " + genderOptional);
        System.out.println("Optional.of(message).get() -> " + genderOptional.get());
        try {
            Optional.of(null);
        } catch (java.lang.NullPointerException e) {
            System.out.println("Optional.of(null) -> java.lang.NullPointerException \n");
        }
    
        System.out.println("Optional.empty() -> " + Optional.empty() + "\n");
    
        System.out.println("Optional.ofNullable(null) -> " + Optional.ofNullable(null));
        System.out.println("Optional.ofNullable(message) -> " + Optional.ofNullable(message));
        System.out.println("Optional.ofNullable(message).get() -> " + Optional.ofNullable(message).get());
    
    }
    

    Output:

    message -> Hello World!
    
    Optional.of(message) -> Optional[Hello World!]
    Optional.of(message).get() -> Hello World!
    Optional.of(null) -> java.lang.NullPointerException 
    
    Optional.empty() -> Optional.empty
    
    Optional.ofNullable(null) -> Optional.empty
    Optional.ofNullable(message) -> Optional[Hello World!]
    Optional.ofNullable(message).get() -> Hello World!
    
    0 讨论(0)
  • 2021-02-07 02:00

    Why would people opt for Optional instead of normal if-else method for null checking?

    The main point of Optional<T> class is to provide a mean for performing null safe mapping operations.

    employeeOptional.map(Employee::getName).map(String::toUpperCase).ifPresent(upperCasedNameConsumer)

    The expression above can replace a cascade of if-else statements in a single readable expression.

    Optional.of provides an assertion for the given argument to be a null-null value, otherwise, you can opt for Optional.ofNullable if you are not sure about the input.

    I strongly recommend you to read the javadoc for Optional<T> class for more optional chaining methods that you can use for your advantage.

    0 讨论(0)
提交回复
热议问题