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 类型不可被序列化, 用作字段类型会出问题的)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值