当前位置:网站首页>Optional common method analysis
Optional common method analysis
2022-08-08 10:32:00 【In ooo】
Optional常用方法解析
Optional 类是一个可以为null的容器对象.Can solve the null pointer exception very well.
创建Optional对象
创建一个空的Optional对象
Optional<String> empty = Optional.empty();
创建一个非空的Optional对象
Optional<String> test = Optional.of("test");
创建一个即可空又可非空的Optional对象
Optional<Object> object = Optional.ofNullable(null);
常见操作
isPresent()
//判断是否为null
Optional<Object> object = Optional.ofNullable(null);
if (object.isPresent()) {
System.out.println(123);
}
get()
//如果OptionalIf there is a value, take it out,否则抛出NoSuchElementException.
Optional<String> test = Optional.ofNullable("test");
if (test.isPresent()) {
String s = test.get();
System.out.println(s);
}
ifPresent()
//如果OptionalIf the instance has a value, the passed in is calledLambda表达式,否则不做处理
Optional<String> test = Optional.ofNullable("test");
test.ifPresent(System.out::println);
orElse()
//如果有值则将其返回,否则返回指定的其它值.
Optional<String> test = Optional.empty();
System.out.println(test.orElse("哈哈哈哈"));
orElseGet()
//与orElse方法类似,但orElse只能传入Optional泛型中的对象
//orElseGet方法可以接受SupplierAn implementation of the interface to generate default values
Optional<String> test = Optional.empty();
test.orElseGet(() -> "123");
map()
//如果有值,则对其执行调用mapping函数得到返回值.如果返回值不为null,则创建包含mapping返回值的Optional作为map方法返回值,否则返回空Optional.
Optional<String> test = Optional.of("12");
Optional<String> s = test.map(x -> x + "12");
s.ifPresent(System.out::println);
flatmap()
//与map方法类似,区别在于mapping函数的返回值不同.map方法的mapping函数返回值可以是任何类型T,而flatMap方法的mapping函数必须是Optional.
Optional<String> test = Optional.of("12");
Optional<String> s = test.flatMap(x -> Optional.of(x + "12"));
s.ifPresent(System.out::println);
filter
//如果有值并且满足断言条件返回包含该值的Optional,否则返回空Optional.
Optional<Integer> integer = Optional.of(12);
Optional<Integer> integer1 = integer.filter(i -> i > 6);
integer1.ifPresent(System.out :: println);
边栏推荐
猜你喜欢
Machine learning model too slow?Look at Intel (R) extension to accelerate
技术分享 | 接口自动化测试之JSON Schema模式该如何使用?
使用.NET简单实现一个Redis的高性能克隆版(三)
idea安装步骤
Loadrunner12.0.2 installation and Chinese language pack installation (Chinese)
目标检测中的Classificition Loss
Vulnhub靶机:GEMINI INC_ 1
Redis 定长队列的探索和实践
牛客收藏上万的神作!这份阿里P8手写的MySQL主从原理手册真的牛
小程序使用npm包
随机推荐
In the.net core, the use of c # realize fastdfs batch file upload more
JSON Schema模式用法
MySQL源码解析之执行计划
实例存储之shelve
功夫再高也怕菜刀,产品经理的那些事
Service Mesh迁移原则
机器学习(十六)推荐系统
四、哈希表
Machine learning model too slow?Look at Intel (R) extension to accelerate
MySQL学习第一部分:认识MySQL
"Inversion of Control" and "Dependency Inversion", can't you tell the difference?
学习笔记:CS520 Knowledge Graphs
图数据库一般用于什么时候呢?
彻底弄清楚session,cookie,sessionStorage,localStorage的区别及应用场景(面试向)
「每周译Go」这次我们来点不一样的!--《How to Code in Go》系列上线
What is intrinsic safety?
详细讲解修改allure报告自定义的logo和名称中文
idea安装步骤
在.net core中,利用C#实现fastdfs多文件批量上传
Redis 定长队列的探索和实践