Opt基本操作

本文转载于gitee Opt作者 方便 自己查阅

修改描述(包括说明bug修复或者添加新特性)

[bug修复] balabala……
[新特性]
对原生Optional的使用区别不大,学习成本低
注释全都汉化并带理解(累瘫)
相比与Optional的新特性都包含在测试用例中
ofBlankAble函数基于ofNullable的逻辑下,额外进行了空字符串判断

首先多层判断null

if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        Country country = address.getCountry();
        if (country != null) {
            String isocode = country.getIsocode();
            if (isocode != null) {
                isocode = isocode.toUpperCase();
            }else{
                    isocode = "2";
            }
        }
    }
}
isocode = Opt.ofNullable(user).map(Address::getAddress).map(Country::getCountry).map(String::getIsocode).orElse("2");
		// ofBlankAble相对于ofNullable考虑了字符串为空串的情况
		String hutool = OptionalBean.ofBlankAble("").orElse("hutool");
		Assert.assertEquals("hutool", hutool);
原版Optional有区别的是,get不会抛出NoSuchElementException
如果想使用原版Optional中的get这样,获取一个一定不为空的值,则应该使用orElseThrow
		// 和原版Optional有区别的是,get不会抛出NoSuchElementException
		// 如果想使用原版Optional中的get这样,获取一个一定不为空的值,则应该使用orElseThrow
		Object opt = OptionalBean.ofNullable(null).get();
		Assert.assertNull(opt);

将jdk11 Optional中的新函数isEmpty,直接照搬了过来

		// 这是jdk11 Optional中的新函数,直接照搬了过来
		// 判断包裹内元素是否为空,注意并没有判断空字符串的情况
		boolean isEmpty = OptionalBean.empty().isEmpty();
		Assert.assertTrue(isEmpty);

将jdk9 Optional中的新函数ifPresentOrElse,直接照搬了过来

		// 这是jdk9中的新函数,直接照搬了过来
		// 存在就打印对应的值,不存在则用{@code System.err.println}打印另一句字符串
		OptionalBean.ofNullable("Hello Hutool!").ifPresentOrElse(System.out::println, () -> System.err.println("Ops!Something is wrong!"));
		OptionalBean.empty().ifPresentOrElse(System.out::println, () -> System.err.println("Ops!Something is wrong!"));

		//个人扩展
		Person p1 = new Person();
        String name = null;
        Opt.ofNullable(name).ifPresentOrElse(p1::setName,() -> p1.setName("小D"));
        System.out.println(p1);

        name = "大D";
        Opt.ofNullable(name).ifPresentOrElse(p1::setName,() -> p1.setName("小D"));
        System.out.println(p1);

结果

Person(name=小D, lenven=null, age=0)
Person(name=大D, lenven=null, age=0)

新增了peek函数,相当于ifPresent的链式调用(个人常用)

		User user = new User();
		// 相当于ifPresent的链式调用
		OptionalBean.ofNullable("hutool").peek(user::setUsername).peek(user::setNickname);
		Assert.assertEquals("hutool", user.getNickname());
		Assert.assertEquals("hutool", user.getUsername());

		// 注意,传入的lambda中,对包裹内的元素执行赋值操作并不会影响到原来的元素
		String name = OptionalBean.ofNullable("hutool").peek(username -> username = "123").peek(username -> username = "456").get();
		Assert.assertEquals("hutool", name);

		//调用测试
        Person p1 = new Person();//业务对象1
        Person p2 = new Person();//业务对象2
        Person p3 = new Person();//业务对象3
        String lenven = null;
        Opt.ofNullable(lenven).peek(p1::setLenven).peek(p2::setLenven).peek(p3::setLenven);//可以对用判断, 用链式的方式一次完成所有操作,对空不操作
        System.out.println(StrUtil.format("业务对象:{}{}{}",p1.getLenven(),p2.getLenven(),p3.getLenven()));
        lenven = "ONE";
        Opt.ofNullable(lenven).peek(p1::setLenven).peek(p2::setLenven).peek(p3::setLenven);
        System.out.println(StrUtil.format("业务对象:{}{}{}",p1.getLenven(),p2.getLenven(),p3.getLenven()));
        //peek 如参为 Consumer 所以可以传具体实现
        Opt.ofNullable(lenven).peek(u->{
            p1.setLenven(CharSequenceUtil.subWithLength(u, 0, 1));
        }).peek(u -> {
            String s = CharSequenceUtil.subWithLength(u, 1, u.length());
            String s1 = CharSequenceUtil.subWithLength(StrUtil.reverse(s), 1, s.length());
            p2.setLenven(StrUtil.reverse(s1));
        }).peek(u -> {
            p3.setLenven(CharSequenceUtil.subWithLength(StrUtil.reverse(u), 0, 1));
        });
        System.out.println(StrUtil.format("业务对象:{}{}{}",p1.getLenven(),p2.getLenven(),p3.getLenven()));

结果

业务对象:nullnullnull
业务对象:ONEONEONE
业务对象:ONE

将jdk9 Optional中的新函数or,直接照搬了过来

		// 这是jdk9 Optional中的新函数,直接照搬了过来
		// 给一个替代的Opt
		String str = OptionalBean.<String>ofNullable(null).or(() -> OptionalBean.ofNullable("Hello hutool!")).map(String::toUpperCase).orElseThrow();
		Assert.assertEquals("HELLO HUTOOL!", str);

		User user = User.builder().username("hutool").build();
		OptionalBean<User> userOptionalBean = OptionalBean.of(user);
		// 获取昵称,获取不到则获取用户名
		String name = userOptionalBean.map(User::getNickname).or(() -> userOptionalBean.map(User::getUsername)).get();
		Assert.assertEquals("hutool", name);

对orElseThrow进行了重载,支持 双冒号+自定义提示语 写法,比原来的

orElseThrow(() -> new IllegalStateException("Ops!Something is wrong!"))

更加优雅,修改后写法为

orElseThrow(IllegalStateException::new, "Ops!Something is wrong!")
测试用例:
		// 获取一个不可能为空的值,否则抛出NoSuchElementException异常
		Object obj = OptionalBean.ofNullable(null).orElseThrow();
		// 获取一个不可能为空的值,否则抛出自定义异常
		Object assignException = OptionalBean.ofNullable(null).orElseThrow(IllegalStateException::new);
		// 获取一个不可能为空的值,否则抛出带自定义消息的自定义异常
		Object exceptionWithMessage = OptionalBean.empty().orElseThrow(IllegalStateException::new, "Ops!Something is wrong!");

用到依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.15</version>
        </dependency>

本文转载于gitee作者 方便 自己查阅

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值