optional的基本方法demo(orElseThrow,ifPresent,orElseGet,FlatMap)

参考下述网址的内容写了一个optional的demo

https://blog.csdn.net/yangxiao_hui/article/details/89853413

import java.util.Optional;
class Scratch {
    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setName("zhangsan1");
        Address address = new Address();
        address.setCity("city");
        user.setAddress(address);
        //orElseThrow
        //test1Old(user);
        test1New(user);
        //ifPresent
        test2Old(user);
        test2New(user);
        //orElseGet
        System.out.println(test3Old(user).toString());
        System.out.println(test3New(user).toString());
        //flatMap map
        //flatMap不会用funcation的结果进行包装,map会包装成Optional
        //所以如果本来就是Optional<String>的属性,直接flatMap就可以了
    }

    public static void test1Old(User user) throws Exception {
        if (user != null) {
            if (user.getAddress() != null) {
                Address address = user.getAddress();
                if (address.getCity() != null) {
                    System.out.println(address.getCity());
                }
            }
        } else {
            throw new Exception("取值错误");
        }
    }

    public static void test1New(User user) throws Exception {
        System.out.println(Optional.ofNullable(user)
                .map(u -> u.getAddress())
                .map(a -> a.getCity())
                .orElseThrow(() -> new Exception("取值错误")));
    }

    public static void test2Old(User user) {
        if (user != null) {
            System.out.println(user.toString());
        }
    }

    public static void test2New(User user) {
        Optional.ofNullable(user).ifPresent(u -> {
            System.out.println(u.toString());
        });
    }

    public static User test3Old(User user) {
        if (user != null) {
            String name = user.getName();
            if ("zhangsan".equals(name)) {
                return user;
            } else {
                user = new User();
                user.setName("LiSi");
            }
        }
        return user;
    }

    public static User test3New(User user) {
        return Optional.ofNullable(user)
                .filter(u -> "zhangsan".equals(u.getName()))
                .orElseGet(() -> {
                    user.setName("LiSi");
                    return user;
                });
    }

    static class User {
        private String name;
        private Address address;

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", address=" + address +
                    '}';
        }

        public void setAddress(Address address) {
            this.address = address;
        }

        public Address getAddress() {
            return address;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    static class Address {
        private String city;

        public void setCity(String city) {
            this.city = city;
        }

        public String getCity() {
            return city;
        }
    }
}

参考文章

  1. https://blog.csdn.net/yangxiao_hui/article/details/89853413
Optional.ofNullable.orElseThrowJavaOptional类的两个方法的组合使用。首先,ofNullable方法接受一个值作为参数,如果该值为非空,则返回一个包含该值的Optional对象;如果该值为空,则返回一个空的Optional对象。\[1\]接着,orElseThrow方法Optional类的另一个方法,它接受一个Supplier函数式接口作为参数,当Optional对象为空时,会抛出一个由Supplier函数式接口提供的异常。\[2\] 举个例子,假设有一个Optional对象u,我们可以使用ofNullable方法将其包装起来,然后使用map方法对其进行一些操作,最后使用orElseThrow方法来处理可能出现的异常情况。如果Optional对象u为空,那么orElseThrow方法会抛出一个CommonException异常,异常的信息为"用户不存在!"。\[3\] 总结起来,optional.ofNullable.orElseThrow的作用是将一个可能为空的值包装成Optional对象,并在值为空时抛出一个指定的异常。 #### 引用[.reference_title] - *1* [Java8-Optional类-ofNullable与orElseThrow](https://blog.csdn.net/manba_yqq/article/details/115742080)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Java8 - Optional.ofNullable orElseThrow](https://blog.csdn.net/qq_42764468/article/details/127251186)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Optional orElseThrow 错误: 未报告的异常错误X; 必须对其进行捕获或声明以便抛出...](https://blog.csdn.net/qq22692150/article/details/111031347)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值