天天看點

Java Optional常用操作

package com.tonis.demo;

import com.tonis.demo.entity.User;

import java.util.Optional;

public class OptionalTest {
    public static void main(String[] args) {
        // Optional執行個體化  of/ofNullable
        Optional emptyOpt = Optional.empty();
        // throw java.lang.NullPointerException
        //Optional ofOpt = Optional.of(null);
        Optional ofNullOpt = Optional.ofNullable(null);

        User user1 = null;
        User user2 = new User(1,"Tom", 20);
        // filter過濾值 map/flatmap轉換值 同stream中對應操作

        // isPresent get
        /**
         * get需在isPresent()方法傳回true時再調用,否則會報異常,如下:
         *      java.util.NoSuchElementException: No value present
         */
        User user = Optional.ofNullable(user1).get();
        // ifPresent
        Optional.ofNullable(user2).ifPresent(e->{
            System.out.println(e.getName());
        });

        // orElse orElseGet 但對象為null時擷取默人值
        /**
         * 當optional域中的值為空時,兩者一樣;當optional域中不為空時,orElse也會執行,orElseGet則不會
         */
        /**
         * out print:
         *      create ...
         *      create 2 ....
         */
        Optional.ofNullable(user1).orElse(createUser());
        Optional.ofNullable(user1).orElseGet(()->{
            System.out.println("create 2 ....");
            return null;
        });
        /**
         *  out print:
         *      create ...
         */
        Optional.ofNullable(user2).orElse(createUser());
        Optional.ofNullable(user2).orElseGet(()->{
            System.out.println("create 2 ....");
            return null;
        });


        /**
         * optional項目中的使用: 鍊式調用
         */
        String result = Optional.ofNullable(user)
                .flatMap(u -> u.getAddress())
                .flatMap(a -> a.getCountry())
                .map(c -> c.getIsocode())
                .orElse("default");
    }

    private static User createUser(){
        System.out.println("create ...");
        return null;
    }
}
           

注:1、使用get前需使用isPresent檢查

       2、Optional 類型用作屬性或是方法參數在 IntelliJ IDEA 中是強力不推薦的

       Reports any uses of java.util.Optional<T>, java.util.OptionalDouble, java.util.OptionalInt, java.util.OptionalLong or com.google.common.base.Optional as the type for a field or a parameter. Optional was designed to provide a limited mechanism for library method return types where there needed to be a clear way to represent “no result”. Using a field with type java.util.Optional is also problematic if the class needs to be Serializable, which java.util.Optional is not. (使用任何像 Optional 的類型作為字段或方法參數都是不可取的. Optional 隻設計為類庫方法的, 可明确表示可能無值情況下的傳回類型. Optional 類型不可被序列化, 用作字段類型會出問題的)