java Optional简单使用场景

1.map判断

// 普通写法
List<Long> dataIds = dataMap.get(data.getFileId());
if (CollectionUtil.isNotEmpty(dataIds)) {
    for (Long id : dataIds) {
        result.put(id, “test”);
    }
}

//Optional配合lambada
Optional.ofNullable(dataMap.get(data.getFileId()))
                    .ifPresent(dataIds ->dataIds.forEach(id -> result.put(id, “test”)));

2.多层null判断

public class TestMain {
    @Data
    public static class Person{
        public Integer id;

        public Person(){}
    }

    @Data
    public static  class Child {
        public Person person;
    }

    @Data
    public static class Parent{
        public Child child;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setId(1);
        Child child = new Child();
        child.setPerson(person);
        Parent parent = new Parent();
        parent.setChild(child);

        //普通写法
        Integer id = null;
        if(parent != null && parent.getChild() != null && parent.getChild().getPerson() != null){
            id = parent.getChild().getPerson().getId();
        }
        System.out.println(id);

        //Optional写法
        Integer id2 = null;
        id2 = Optional.ofNullable(parent)
                .map(Parent::getChild)
                .map(Child::getPerson)
                .map(Person::getId)
                .orElse(null);
        System.out.println(id2);
    }

3.初始化

List<String> list = null;
list = Optional.ofNullable(list).orElseGet(ArrayList::new);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值