Java8–Optional使用范例
Java8–Optional使用范例
1.尽量避免使用get()方法
下面是get方法的源码,当值为null的时候,会抛出异常,这和我们使用该类方法的目的冲突,我们的目的就是尽可能消灭异常.
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
// 这样和null判断没什么区别 最好别这么用
Optional<String> str = Optional.of("Hello world");
if (str.isPresent()){
str.get();
}
2.尽量避免使用isPresent()方法
3.不要作为类的实例属性 Optional是容器
4.不要作为方法参数
5.正确使用举例
1、ifPresent()判断替换if
//待优化
String referer = request.getHeader("referer");
if (StringUtils.isNotEmpty(referer)) {
request.getSession().setAttribute("referer", referer);
}
//java8
Optional.ofNullable(request.getHeader("referer"))
.ifPresent(s -> {
request.getSession().setAttribute("referer", s);
});
2、用orElse替换 if...else...
//待优化
String redirect = (String) session.getAttribute("referer");
if (redirect == null){
result.put("referer","/index");
}else {
result.put("referer",redirect);
}
//java8
Optional<String> redirect = Optional.ofNullable((String) session.getAttribute("referer"));
result.put("referer",redirect.orElse("/index"));
3、用orElseThrow替换 throw new Exception
//原写法
ProblemBLOBs problem = problemService.selectByPrimaryKey(id);
if (problem == null){
throw new PageException(PROBLEM_NOT_EXIST);
}
model.addAttribute("problem",problem);
//新写法
Optional<ProblemBLOBs> problem = Optional.ofNullable(problemService.selectByPrimaryKey(id));
// 使用抛出异常
model.addAttribute("problem", problem.orElseThrow(() -> new PageException(PROBLEM_NOT_EXIST)));
4、方法的返回值最好也能用Optional包装,这样调用方也好判断是否为空
5、Optional的经典使用
package com.fjh.jvm;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class OptionnalTest {
public static void main(String[] args) {
Employee employee1 = new Employee("employee1");
Employee employee2 = new Employee("employee1");
Company company = new Company("company");
List<Employee> list = Arrays.asList(employee1,employee2);
company.setEmployees(list);
// 判断公司里面有没有员工 由返回员工列表 没有返回一个空的集合
Optional<Company> optional = Optional.ofNullable(company);
System.out.println(optional.map(com -> com.getEmployees()).orElse(Collections.emptyList()));
}
}
关注公众号
低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
Schedulerx2.0分布式执行之——广播执行
1. 简介 广播执行表示一个任务实例会广播到该分组所有worker上执行,当所有机器都执行完成,该实例才算完成。 任意一台worker执行失败,都算该实例失败。 所有worker执行成功,才算该实例成功。 有子任务列表,可以看每台机器的执行详情。 2. 执行方式 执行方式选择广播 3. 任务类型 任务类型可以选择多种,比如脚本,或者java任务。如果选择java,还支持preProcess和postProcess高级特性。 使用java任务需要继承JavaProcessor(1.0.8+版本),接口如下: public ProcessResult process(JobContext context) throws Exception; (必选) public void preProcess(JobContext context); (可选) pub
-
下一篇
Python 小抄报
python备忘录大全 下载文档地址, PDF, Fork me on GitHub or Check out FAQ. 内容 1. Collections: List__,__ Dictionary__,__ Set__,__ Tuple__,__ Range__,__ Enumerate__,__ Iterator__,__ Generator__.__ 2. Types: Type__,__ String__,__ Regular_Exp__,__ Format__,__ Numbers__,__ Combinatorics__,__ Datetime__.__ 3. Syntax: Args__,__ Inline__,__ Closure__,__ Decorator__,__ Class__,__ Duck_Types__,__ Enum__,__ Exceptions__.__ 4. System: Print__,__ Input__,__ Command_Line_Arguments__,__ Open__,__ Path__,__ Command_E...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- CentOS6,CentOS7官方镜像安装Oracle11G
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- SpringBoot2全家桶,快速入门学习开发网站教程
- CentOS7设置SWAP分区,小内存服务器的救世主
- Crontab安装和使用
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- CentOS7,8上快速安装Gitea,搭建Git服务器
- CentOS7编译安装Cmake3.16.3,解决mysql等软件编译问题
- Windows10,CentOS7,CentOS8安装Nodejs环境

微信收款码
支付宝收款码