[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
介绍
Optional是java8引进的一个类,它能让开发者更好的规范代码。可以尽量避免空指针的出现。
创建
String str = "Optional"; Optional<String> empty = Optional.empty();
Optional<String> str1 = Optional.of(str); Optional<String> str2 =
Optional.ofNullable(str);
Optional创建有三种方法。
* Optional.empty() 直接创建一个空的Optional实例对象
* Optional.of(T t) 创建一个泛型Optional实例对象,当入参为null时会抛出异常
* Optional.offNullable(T t) 和2相同,支持传入null对象
取值
Optional使用get()方法取值,当Optional容器为空时,使用get()取值则会抛出异常
调用方法
* isEmpty() : 该方法可以判断Optional容器是否为空,为空返回true,否则返回false
* orElse(T t):该方法可以获取Optional容器值,如果容器为空则取入参值。可以在不清楚容器是否存在值时使用当前方法获取值
* isPresent(): 该方法对Optional容器内值进行判断,如果存在则可以进行某些操作该方法里面放的是一个Consumer函数式接口
如下操作:
String str = "Optional"; Optional<String> str1 = Optional.of(str);
str1.ifPresent(new Consumer<String>() { @Override public void accept(String s)
{ System.out.println("不为空执行的方法"); } });
stream流操作
Optional可以进行stream流操作。演示如下
String str = "Optional"; Optional<String> str1 = Optional.of(str);
List<String> collect = str1.stream().filter(item -> item.equals("Optional"))
.collect(Collectors.toList()); System.out.println(JSON.toJSONString(collect));
输出结果如下