1. 程式人生 > >java1.8新特性(optional 使用)

java1.8新特性(optional 使用)

 

  經常在程式中出現 java.lang.NullPointerException  為了避免  報錯,總是要進行一些 是否為null 的if else 判斷 ,1.8 可以使用optional 類 來簡化處置
   optional :A container object which may or may not contain a non-null value.:可能包含也可能不包含非空值的容器物件。

  •      既然optional 是一個容器物件,那就應該先建立該 物件 才能呼叫該物件的一些方法 建立optional的方式: 
  1. 呼叫Optional靜態方法.empty()  來建立一個optional 容器物件 
    /**
         * Returns an empty {@code Optional} instance.  No value is present for this
         * Optional.
         *
         * @apiNote Though it may be tempting to do so, avoid testing if an object
         * is empty by comparing with {@code ==} against instances returned by
         * {
    @code Option.empty()}. There is no guarantee that it is a singleton. * Instead, use {@link #isPresent()}. * * @param <T> Type of the non-existent value * @return an empty {@code Optional} */ public static<T> Optional<T> empty() { @SuppressWarnings(
    "unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; }
    public static void testOptional() {
            Optional<Object> empty = Optional.empty();
        }
  2. optional 的建構函式 許可權是private 的 所以 不能直接通過建構函式的方法 生成該物件,呼叫靜態方法of(T t) 可以建立一個指定引數的optional  
    /**
         * Returns an {@code Optional} with the specified present non-null value.
         *
         * @param <T> the class of the value
         * @param value the value to be present, which must be non-null
         * @return an {@code Optional} with the value present
         * @throws NullPointerException if value is null
         */
        public static <T> Optional<T> of(T value) {
            return new Optional<>(value);
        }
    public static void testOptional() {
            // 使用 Optional.empty() 建立 Optional 物件
            Optional<Object> empty = Optional.empty();
            // 私有化建構函式 不能直接 建立
            // Optional<User> optional = new Optional(new User());
            // 使用 Optional.of() 建立 Optional 物件
            Optional<User> optional = Optional.of(new User());
        }

     

  3. Opional 有一個靜態方法 ofNullable(T t)可以 根據你傳入的值 來 來判斷呼叫 Optional的無參構造方法還是呼叫 optional 的有參構造方法 如果是null 則呼叫 empty() 為空 則呼叫 of(T t) 方法
    /**
         * Returns an {@code Optional} describing the specified value, if non-null,
         * otherwise returns an empty {@code Optional}.
         *
         * @param <T> the class of the value
         * @param value the possibly-null value to describe
         * @return an {@code Optional} with a present value if the specified value
         * is non-null, otherwise an empty {@code Optional}
         */
        public static <T> Optional<T> ofNullable(T value) {
            return value == null ? empty() : of(value);
        }
    public static void testOptional() {
            // 使用 Optional.empty() 建立 Optional 物件
            Optional<Object> empty = Optional.empty();
            // 私有化建構函式 不能直接 建立
            // Optional<User> optional = new Optional(new User());
            // 使用 Optional.of() 建立 Optional 物件
            Optional<User> optional = Optional.of(new User());
            //使用 Optional.ofNullable() 建立 Optional 物件
            Optional<Object> ofNullable = Optional.ofNullable(null);
        }

     

  • 以上三種方法 都可以建立一個Optional 物件,如何使用該物件的方法
  1. 獲取 optional 的值  呼叫 get()方法 如果 為null 則丟擲異常
        /**
         * If a value is present in this {@code Optional}, returns the value,
         * otherwise throws {@code NoSuchElementException}.
         *
         * @return the non-null value held by this {@code Optional}
         * @throws NoSuchElementException if there is no value present
         *
         * @see Optional#isPresent()
         */
        public T get() {
            if (value == null) {
                throw new NoSuchElementException("No value present");
            }
            return value;
        }

  2. 檢測 optional的值是否為空 如果 為空 則 false  

        /**
         * Return {@code true} if there is a value present, otherwise {@code false}.
         *
         * @return {@code true} if there is a value present, otherwise {@code false}
         */
        public boolean isPresent() {
            return value != null;
        }
    package lambda.stream;
    
    import java.util.Optional;
    
    /**
     * @author 作者:cb
     * @version 建立時間:2019年1月14日 上午11:12:12
     * 
     */
    public class OptionalDemo {
        public static void main(String[] args) {
            testIsPresent();
        }
    
        public static void testIsPresent() {
            Optional<User> optional = Optional.ofNullable(new User());
            boolean flag = optional.isPresent();
            System.out.println(flag);
            optional = Optional.ofNullable(null);
            flag = optional.isPresent();
            System.out.println(flag);
        }
    }
    true
    false

     

  3. optional 可以根據  ifPresent 來對 值T  進行 自身的處理 
        /**
         * If a value is present, invoke the specified consumer with the value,
         * otherwise do nothing.
         *
         * @param consumer block to be executed if a value is present
         * @throws NullPointerException if value is present and {@code consumer} is
         * null
         */
        public void ifPresent(Consumer<? super T> consumer) {
            if (value != null)
                consumer.accept(value);
        }
    public class OptionalDemo {
        public static void main(String[] args) {
            testIfPresent();
            // testIsPresent();
        }
    
        public static void testIfPresent() {
            Optional<User> optional = Optional.ofNullable(new User());
            optional.ifPresent((age) -> age.setAge(100));
            System.out.println(optional.get().getAge());
    
        }
    100

     

  4. 檢測一個使用者的名稱是否 滿足 特定條件的時候 ,optional 的filter 方法 
        /**
         * If a value is present, and the value matches the given predicate,
         * return an {@code Optional} describing the value, otherwise return an
         * empty {@code Optional}.
         *
         * @param predicate a predicate to apply to the value, if present
         * @return an {@code Optional} describing the value of this {@code Optional}
         * if a value is present and the value matches the given predicate,
         * otherwise an empty {@code Optional}
         * @throws NullPointerException if the predicate is null
         */
        public Optional<T> filter(Predicate<? super T> predicate) {
            Objects.requireNonNull(predicate);
            if (!isPresent())
                return this;
            else
                return predicate.test(value) ? this : empty();
        }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    
    /**
     * @author 作者:cb
     * @version 建立時間:2019年1月14日 上午11:12:12
     * 
     */
    public class OptionalDemo {
        public static void main(String[] args) {
            testFilter();
            // testIfPresent();
            // testIsPresent();
        }
    
        public static void testFilter() {
            Optional<User> ofNullable = Optional.ofNullable(new User("Tom", 15));
            Optional<User> filter = ofNullable.filter(user -> user.getAge() == 15);
        }
    User [name=Tom, age=15]

    如果 沒有滿足 條件是 15的  返回值列印 報錯

    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    
    /**
     * @author 作者:cb
     * @version 建立時間:2019年1月14日 上午11:12:12
     * 
     */
    public class OptionalDemo {
        public static void main(String[] args) {
            testFilter();
            // testIfPresent();
            // testIsPresent();
        }
    
        public static void testFilter() {
            Optional<User> ofNullable = Optional.ofNullable(new User("Tom", 25));
            Optional<User> filter = ofNullable.filter(user -> user.getAge() == 15);
        
    Exception in thread "main" java.util.NoSuchElementException: No value present
        at java.util.Optional.get(Optional.java:135)
        at lambda.stream.OptionalDemo.testFilter(OptionalDemo.java:25)
        at lambda.stream.OptionalDemo.main(OptionalDemo.java:16)

     

  5. Optional 物件中map的使用:返回 User物件的 name屬性
        /**
         * If a value is present, apply the provided mapping function to it,
         * and if the result is non-null, return an {@code Optional} describing the
         * result.  Otherwise return an empty {@code Optional}.
         *
         * @apiNote This method supports post-processing on optional values, without
         * the need to explicitly check for a return status.  For example, the
         * following code traverses a stream of file names, selects one that has
         * not yet been processed, and then opens that file, returning an
         * {@code Optional<FileInputStream>}:
         *
         * <pre>{@code
         *     Optional<FileInputStream> fis =
         *         names.stream().filter(name -> !isProcessedYet(name))
         *                       .findFirst()
         *                       .map(name -> new FileInputStream(name));
         * }</pre>
         *
         * Here, {@code findFirst} returns an {@code Optional<String>}, and then
         * {@code map} returns an {@code Optional<FileInputStream>} for the desired
         * file if one exists.
         *
         * @param <U> The type of the result of the mapping function
         * @param mapper a mapping function to apply to the value, if present
         * @return an {@code Optional} describing the result of applying a mapping
         * function to the value of this {@code Optional}, if a value is present,
         * otherwise an empty {@code Optional}
         * @throws NullPointerException if the mapping function is null
         */
        public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
            Objects.requireNonNull(mapper);
            if (!isPresent())
                return empty();
            else {
                return Optional.ofNullable(mapper.apply(value));
            }
        }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    
    /**
     * @author 作者:cb
     * @version 建立時間:2019年1月14日 上午11:12:12
     * 
     */
    public class OptionalDemo {
        public static void main(String[] args) {
            testMap();
            // testIfPresent();
            // testIsPresent();
        }
    
        public static void testMap() {
            Optional<User> ofNullable = Optional.ofNullable(new User("Tom", 25));
            Optional<String> map = ofNullable.map(user -> user.getName());
            System.out.println(map.get());
        }

    結果:

    Tom

     

  6. Optional 的orElse 方法 
        /**
         * Return the value if present, otherwise return {@code other}.
         *
         * @param other the value to be returned if there is no value present, may
         * be null
         * @return the value, if present, otherwise {@code other}
         */
        public T orElse(T other) {
            return value != null ? value : other;
        }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    
    /**
     * @author 作者:cb
     * @version 建立時間:2019年1月14日 上午11:12:12
     * 
     */
    public class OptionalDemo {
        public static void main(String[] args) {
            testOrelse();
            // testIfPresent();
            // testIsPresent();
        }
    
        public static void testOrelse() {
            Optional<User> ofNullable = Optional.ofNullable(null);
            User orElse = ofNullable.orElse(new User("Tom", 35));
            System.out.println(orElse);//結果:User [name=Tom, age=35] 
        }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    
    /**
     * @author 作者:cb
     * @version 建立時間:2019年1月14日 上午11:12:12
     * 
     */
    public class OptionalDemo {
        public static void main(String[] args) {
            testOrelse();
            // testIfPresent();
            // testIsPresent();
        }
    
        public static void testOrelse() {
            Optional<User> ofNullable = Optional.ofNullable(new User("jack", 45));
            User orElse = ofNullable.orElse(new User("Tom", 35));
            System.out.println(orElse);//結果:User [name=jack, age=45]
    
        }

     

  7. Optional 的orElseGet方法  方法用處和orElseGet 一樣只是 傳遞的引數 型別 不一樣 一個是T  一個 function型別的介面
        /**
         * Return the value if present, otherwise invoke {@code other} and return
         * the result of that invocation.
         *
         * @param other a {@code Supplier} whose result is returned if no value
         * is present
         * @return the value if present otherwise the result of {@code other.get()}
         * @throws NullPointerException if value is not present and {@code other} is
         * null
         */
        public T orElseGet(Supplier<? extends T> other) {
            return value != null ? value : other.get();
        }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    
    /**
     * @author 作者:cb
     * @version 建立時間:2019年1月14日 上午11:12:12
     * 
     */
    public class OptionalDemo {
        public static void main(String[] args) {
            testOrElseGet();
            // testIfPresent();
            // testIsPresent();
        }
    
        public static void testOrElseGet() {
            Optional<User> ofNullable = Optional.ofNullable(new User("jack", 45));
            User orElseGet = ofNullable.orElseGet(() -> new User("Tom", 35));
            System.out.println(orElseGet);// 結果:User [name=Tom, age=35]
    
        }

     

  8. optional 的flatMap使用(扁平化):