当前位置:网站首页>Optional empty judgment operation
Optional empty judgment operation
2022-07-20 05:58:00 【Java interview 365】
Optional Sentenced to empty
JAVA stay 1.8 Version launch Optional, Official documents describe it as Container objects that may or may not contain non null values , at present Optional Used to avoid program exceptions NullPointerException.
Code emulation
// All classes below are omitted set,get Method
public class Employee {
private String employeeName;
private Team team;
}
public class Team {
private String teamName;
private Department department;
public Team(String teamName) {
this.teamName = teamName;
}
}
public class Department {
private String departmentName;
private Company company;
}
public class Company {
private String companyName;
}
Test code
// Because it was not initialized at the time of creation Team Object's Department attribute , Causes subsequent calls to null pointers
public void testCompany(){
Employee employee = new Employee();
employee.setEmployeeName("zhangsan");
employee.setTeam(new Team("xxx Product group "));
System.out.println(employee.getTeam().getDepartment().getCompany().getCompanyName());
}
At this time, if we adopt the traditional method, the general blank judgment code is as follows
public void testCompanyAvoidNPE(){
Employee employee = new Employee();
employee.setEmployeeName("zhangsan");
employee.setTeam(new Team("xxx Product group "));
Team team = employee.getTeam();
if (team == null){
System.out.println(" Abnormal pull , The parameter is empty. !");
return;
}
Department department = team.getDepartment();
if (department == null){
System.out.println(" Abnormal pull , The parameter is empty. !");
return;
}
Company company = department.getCompany();
if (company == null){
System.out.println(" Abnormal pull , The parameter is empty. !");
return;
}
String companyName = company.getCompanyName();
System.out.println(companyName);
}
Obviously, this kind of empty code causes the expansion of business code , Code readability is extremely low , So in this scenario, we need to learn 1.8 Launched empty container object Optional.
Optional Common methods
establish Optional object
JAVA Three static methods are provided for building Optional The objects are as follows
Return value | Method and description |
---|---|
static <T> Optional<T> | empty() Returns an empty Optional example . |
static <T> Optional<T> | of(T value) Returns a Optional The current non null value of Optional. |
static <T> Optional<T> | ofNullable(T value) Return to one Optional Specified value Optional, If it is not empty , Then return an empty Optional . |
public void createOptionalObject(){
System.out.println(Optional.empty());
// Pass on null Empty pointer
// System.out.println(Optional.of(null));
System.out.println(Optional.of(new String("1111")));
// Pass on null call Optional.empty()
System.out.println(Optional.ofNullable(null));
System.out.println(Optional.ofNullable(new Content("111"," Test content ")));
}
class Content {
private String id;
private String value;
public Content() {
}
public Content(String id, String value) {
this.id = id;
this.value = value;
}
// Omit get,set Method
}
The results are as follows
Optional.empty
Optional[1111]
Optional.empty
Optional[Content{id=‘111’, value=‘ Test content ’}]
It is recommended to use ofNullable, Because it can handle null or non null values , The code is as follows
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
Common functional methods
Method name | Return value | Function description |
---|---|---|
isPresent() | boolean | Judge Optional Whether the object exists , There is true non-existent false |
ifPresent(Consumer<? super T> consumer) | void | If Optional Object exists to execute consumer Consumer interface , There is no execution |
get | T | return Optional Object encapsulated object T data , Note that the actual object may throw an exception if it is empty |
orElse(T other) | T | If Optional If the object exists, the encapsulated object data is returned , Returns if none exists T other data , Equivalent to no default value |
orElseGet(Supplier<? extends T> other) | T | yes orElse Method upgrade , The difference lies in orElse Method passes in a fixed default value , This method is a supply function method , If Optional If the object is empty, execute other The method logic of |
orElseThrow(Supplier<? extends X> exceptionSupplier) | <X extends Throwable>T | Same as orElse Method upgrade , When Optional If the object is empty, execute exceptionSupplier Method , Finally throw an exception |
filter(Predicate<? super T> predicate) | Optional<T> | When Optional The object satisfies predicate The matching rule in the assertion function returns , Otherwise, it returns empty Optional |
map(Function<? super T,? extends U> mapper) | <U> Optional<U> | To be able to Optional Object value processing of is converted to another instance object value , And generate a new type Optional object , If the new object generated is null, Then return an empty Optional object |
flatMap(Function<? super T,Optional<U>> mapper) | <U> Optional<U> | and map similar , however map The operation is the specific object , and flatMap The return is Optional Encapsulated objects |
The code is shown as follows
public void testOptionFunction(){
//===============================isPresent()================================
// false
System.out.println(Optional.empty().isPresent());
// Optional[Content{id='222', value=' test '}]
System.out.println(Optional.ofNullable(new Content("222"," test ")));
//===============================ifPresent()================================
// Not empty print :Content{id='222', value=' test '} If it is empty, do not execute
Optional.ofNullable(new Content("222"," test ")).ifPresent(e->{
System.out.println(" Not empty print :"+e);
});
//===============================get()================================
// NoSuchElementException: No value present
try {
System.out.println(Optional.empty().get());
}catch (Exception e){
e.printStackTrace();
}
// Content{id='222', value=' test '}
System.out.println(Optional.ofNullable(new Content("222"," test ")).get());
//===============================orElse()================================
// Content{id='0', value=' Default '}
System.out.println(Optional.empty().orElse(new Content("0"," Default ")));
//===============================orElseGet()================================
// Content{id='333', value=' test orElseGet'}
System.out.println(Optional.empty().orElseGet(() -> {
Content content = new Content("333", " test orElseGet");
return content;
}));
// Content{id='222', value=' test '}
System.out.println(Optional.ofNullable(new Content("222", " test ")).orElseGet(() -> {
Content content = new Content("444", " test orElseGet");
return content;
}));
//===============================orElseThrow()================================
// java.lang.Exception: The parameter is empty.
try {
Optional.empty().orElseThrow(()->{
return new Exception(" The parameter is empty. ");
});
} catch (Exception e) {
e.printStackTrace();
}
//===============================filter()================================
// "555".equals(e.getId()); Optional[Content{id='555', value=' test '}]
// "5565".equals(e.getId()); Optional.empty
System.out.println(Optional.ofNullable(new Content("555", " test ")).filter(e -> {
return "5565".equals(e.getId());
}));
}
map and flatMap
public void testOptionMapFunction(){
Optional<Content> optionalContent = Optional.ofNullable(new Content("777"," test Map"));
Optional<Content> optionalContent1 = optionalContent.map(e -> {
String id = e.getId();
String value = e.getValue();
return e;
});
Optional<Content> optionalContent2 = optionalContent.flatMap(e -> {
String id = e.getId();
String value = e.getValue();
// The difference is here , One is that it can be converted to another instance object , One is to convert to Optional Packaging object
return Optional.of(e);
});
// The final effect is similar
System.out.println(optionalContent1);
System.out.println(optionalContent2);
}
Use Optional Certain ratio null Okay?
This is obviously wrong , If used as follows , Actually sum null There is no difference in direct air judgment
public static void main(String[] args) {
Optional<Content> optionalContent = Optional.ofNullable(null);
// Direct error
optionalContent.get();
}
// Upgrade writing
public static void main(String[] args) {
Optional<Content> optionalContent = Optional.ofNullable(null);
// Judge not empty
if (optionalContent.isPresent()){
System.out.println(optionalContent.get());
}
}
null Direct judgment of empty
public static void main(String[] args) {
Content content = new Content();
if (content != null){
System.out.println(content);
}
}
The correct wording is as follows
public static void main(String[] args) {
Optional<Content> optionalContent = Optional.ofNullable(null);
// Non empty time executes the logic in the consumer interface
optionalContent.ifPresent(content -> {
System.out.println(content);
});
}
Someone here may say , If if{}else{} How to deal with the logic that needs to be written inside
public static void main(String[] args) {
Optional<Content> optionalContent = Optional.ofNullable(null);
Content content = optionalContent.map(e -> {
// Do some business
// The return value can be any type of value , You can return a string , however orElseGet You need to keep the returned string consistent
return e;
}).orElseGet(() -> {
// Do some business
return new Content("0", " The default value is ");
});
System.out.println(content);
}
Optional Use scenarios
Reduce tedious non empty judgments
As mentioned earlier testCompanyAvoidNPE Example in method , You can use Optional To simplify the
public void testCompanyAvoidNPE2(){
Employee employee = new Employee();
employee.setEmployeeName("zhangsan");
employee.setTeam(new Team("xxx Product group "));
// This is equivalent to chain operation
String companyName = Optional.ofNullable(employee)
.map(employee1 -> employee1.getTeam())
.map(team -> team.getDepartment())
.map(department -> department.getCompany())
.map(company -> company.getCompanyName())
.orElse("no company");
System.out.println(companyName);
}
Set the default value to the bottom
// Original method
public String setDefaultValue1(Content content){
if (ObjectUtils.isEmpty(content)){
return "0";
}
if (StringUtils.isEmpty(content.getId())){
String id = "0";
content.setId(id);
}
return content.getId();
}
// use Optional
public String setDefaultValue2(Content content){
String id = Optional.ofNullable(content)
.map(content1 -> content1.getId())
.orElse("0");
return id;
}
Optional Try to use only as the return type of the method
Note that we use Optional The ultimate goal of is to avoid appearing in the program null Object exception , So we can use Optional As the return value type of the method , But also pay attention Optional Although good, don't abuse , Just use it properly .
边栏推荐
猜你喜欢
Chapter VIII tasks and functions
互联网大厂智能座舱斗法
(二)fastai 2019 part2 重点提炼
Intelligent cockpit fighting method of Internet manufacturers
Intelligent cockpit fighting method of Internet manufacturers
Security researchers found malware targeting industrial operators
TCP实验验证
[OC学习笔记]GCD复习
VMware虚拟机的概念和安装
【测量学】第一章测绘工作概述
随机推荐
某翻译js逆向,调用栈简单用法
[intelligent hardware] Jetson Nana extended video memory (memory)
LeetCode-394-字符串解码
js数据类型获取
小白新手再启牛开通银河证券靠谱安全吗?
Zabbix5.0配置企业微信告警
They gathered at the 2022 ecug con just for "China's technological power"
Hello World 凑个数
The difference between direct access and method access for parent-child attributes with the same name
Docker安装Redis!!!(含每一步详细图解)实战
Intelligent cockpit fighting method of Internet manufacturers
selenium的窗口切换
Is it safe for GF Securities to open a mobile account? What is the threshold
安全研究人员发现针对工业运营商的恶意软件
Selenium's pull-down + headless browser
Math. LM method of net optimization method
1. 课程内容介绍
An Improved One millisecond Mobile Backbone 论文笔记
洛谷P1016 [NOIP1999 提高组] 旅行家的预算 题解
Introduction and use of finalshell