Uses for Optional

前端 未结 14 1421
眼角桃花
眼角桃花 2020-11-22 01:01

Having been using Java 8 now for 6+ months or so, I\'m pretty happy with the new API changes. One area I\'m still not confident in is when to use Optional. I se

14条回答
  •  梦如初夏
    2020-11-22 01:26

    Java SE 8 introduces a new class called java.util.Optional,

    You can create an empty Optional or Optional with null value.

    Optional emptyOptional = Optional.empty(); 
    

    And here is an Optional with a non-null value:

    String valueString = new String("TEST");
    Optional optinalValueString = Optional.of(valueString );
    

    Do Something If a Value Is Present

    Now that you have an Optional object, you can access the methods available to explicitly deal with the presence or absence of values. Instead of having to remember to do a null check, as follows:

    String nullString = null;
    if (nullString != null) {
        System.out.println(nullString);
    }
    

    You can use the ifPresent() method, as follows:

    Optional optinalString= null;
    optinalString.ifPresent(System.out::println);
    
    package optinalTest;
    
    import java.util.Optional;
    
    public class OptionalTest {
        public Optional getOptionalNullString() {
            return null;
    //      return Optional.of("TESt");
        }
    
        public static void main(String[] args) {
    
            OptionalTest optionalTest = new OptionalTest();
    
            Optional> optionalNullString = Optional.ofNullable(optionalTest.getOptionalNullString());
    
            if (optionalNullString.isPresent()) {
                System.out.println(optionalNullString.get());
            }
        }
    }
    

提交回复
热议问题