当前位置:网站首页>Summary of empty string judgment in the project
Summary of empty string judgment in the project
2022-07-01 14:55:00 【Xiaoqu classmate】
In the project , I believe that many partners have been java Of NPE(Null Pointer Exception) The so-called null pointer makes you dizzy , Somebody said “ Prevent null pointer exception , It is the basic cultivation of programmers .” But cultivation belongs to cultivation , It is also one of the most troublesome problems for our programmers , So today we're going to make the most of Java8 New features
Optional
To simplify the code as much as possible and deal with NPE(Null Pointer Exception Null pointer exception ).
Summary of empty string judgment in the project
- 1、 know Optional And use
- 1.1、Optional objects creating
- 1.2 、Optional.get() Method ( Returns the value of the object )
- 1.3、Optional.isPresent() Method ( Judge whether it is empty )
- 1.4、Optional.ifPresent() Method ( Judge whether it is empty and return the function )
- 1.5、Optional.filter() Method ( Filter objects )
- 1.6、Optional.map() Method ( Object is repackaged )
- 1.7、Optional.flatMap() Method (Optional Object is repackaged )
- 1.8、Optional.orElse() Method ( Null returns the object )
- 1.9、Optional.orElseGet() Method ( Empty return Supplier object )
- 1.10、Optional.orElseThrow() Method ( Null returns an exception )
1、 know Optional And use
Simply speaking ,java Provided Opitonal
Class is Java It is provided to solve the problem that we usually judge whether the object is empty , Will use null!=obj
Such a way to judge the existence of , So as to solve the headache caused by NPE(Null Pointer Exception Null pointer exception ), meanwhile Optional
The existence of can make the code simpler , More readable , Code is more efficient to write .
Conventional judgment :
// object people
// Attributes are name,age
Person person=new Person();
if (null==person){
return "person by null";
}
return person;
Use Optional:
// object people
// Attributes are name,age
Person person=new Person();
return Optional.ofNullable(person).orElse("person by null");
Test presentation class Person Code ( If a friend doesn't understand, you can take a look at this ):
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
1.1、Optional objects creating
First of all, let's turn it on Optional Internal , Go and find out First create a few Optional Object extraction method .
public final class Optional<T> {
private static final Optional<?> EMPTY = new Optional<>();
private final T value;
// We can see that both construction squares are private Private
// explain We can't go outside new come out Optional object
private Optional() {
this.value = null;
}
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
// This static method is roughly Is to create an object with an empty wrapper value, because there is no parameter assignment
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
// This static method is roughly Is to create an object with non empty packing value Because of the assignment
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
// This static method is roughly If parameters value It's empty , Create an empty object , If it's not empty , Then create a parameter object
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
}
Then make a simple example to show Corresponding to the above
// 1、 Create a wrapper object with an empty value Optional object
Optional<String> optEmpty = Optional.empty();
// 2、 Create a wrapper object whose value is not empty Optional object
Optional<String> optOf = Optional.of("optional");
// 3、 The value of the created wrapper object can be empty or not Optional object
Optional<String> optOfNullable1 = Optional.ofNullable(null);
Optional<String> optOfNullable2 = Optional.ofNullable("optional");
1.2 、Optional.get() Method ( Returns the value of the object )
get() The method is to return a option Instance value of Source code :
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
That is, if value If it is not empty, return , If it is empty, an exception is thrown “No value present” Simple examples show :
Person person=new Person();
person.setAge(2);
Optional.ofNullable(person).get();
1.3、Optional.isPresent() Method ( Judge whether it is empty )
isPresent
() The method is to return a boolean Type values , True if the object is not empty , If it is empty, then false Source code :
public Boolean isPresent() {
return value != null;
}
A simple example shows :
Person person=new Person();
person.setAge(2);
if (Optional.ofNullable(person).isPresent()){
// Write non empty logic
System.out.println(" Not empty ");
} else{
// Write empty logic
System.out.println(" It's empty ");
}
1.4、Optional.ifPresent() Method ( Judge whether it is empty and return the function )
This means that if the object is not empty , Then run the function body Source code :
public void ifPresent(Consumer<? super T> consumer) {
// If value Not empty , Then run accept Method body
if (value != null)
consumer.accept(value);
}
See examples :
Person person=new Person();
person.setAge(2);
Optional.ofNullable(person).ifPresent(p -> System.out.println(" Age "+p.getAge()));
If the object is not empty , Will print this age , Because it has been done internally NPE( Judge not empty ), So don't worry about null pointer exceptions .
1.5、Optional.filter() Method ( Filter objects )
filter()
The method roughly means , Accept an object , Then filter him conditionally , If the conditions are met, return Optional Object itself , If it does not match, it returns null Optional
.
Source code :
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
// Return directly if it is empty this
if (!isPresent())
return this; else
// Determine whether the return itself is empty Optional
return predicate.test(value) ? this : empty();
}
A simple example :
Person person=new Person();
person.setAge(2);
Optional.ofNullable(person).filter(p -> p.getAge()>50);
1.6、Optional.map() Method ( Object is repackaged )
map() The method will correspond to Funcation Objects in functional interfaces , Perform a quadratic operation , Encapsulate it into a new object and return it in Optional in
Source code :
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
// If it is empty, return yourself
if (!isPresent())
return empty();
else {
// Otherwise, return the method decorated Optional
return Optional.ofNullable(mapper.apply(value));
}
}
Example show :
Person person1=new Person();
person.setAge(2);
String optName = Optional.ofNullable(person).map(p -> person.getName()).orElse("name It's empty ");
1.7、Optional.flatMap() Method (Optional Object is repackaged )
map() The method will correspond to Optional< Funcation > Objects in functional interfaces , Perform a quadratic operation , Encapsulate it into a new object and return it in Optional in
Source code :
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty(); else {
return Objects.requireNonNull(mapper.apply(value));
}
}
Example
Person person=new Person();
person.setAge(2);
Optional<Object> optName = Optional.ofNullable(person).map(p -> Optional.ofNullable(p.getName()).orElse("name It's empty "));
1.8、Optional.orElse() Method ( Null returns the object )
One of the common methods , This method means that if the wrapper object is empty , Is executed orElse In the method value, If it is not empty , The write object is returned
Source code :
public T orElse(T other) {
// If it is not empty , return value, If it is empty , return other
return value != null ? value : other;
}
1.9、Optional.orElseGet() Method ( Empty return Supplier object )
This with orElse Very similar , It's not the same as joining , The parameter for Supplier object , Null returns the of the incoming object .get() Method , If it is not empty, the current object is returned
Source code :
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
Example :
Optional<Supplier<Person>> sup=Optional.ofNullable(Person::new);
// call get() Method , Only then will the constructor of the object be called , Get the real object
Optional.ofNullable(person).orElseGet(sup.get());
1.10、Optional.orElseThrow() Method ( Null returns an exception )
Personally, I often use this method in actual combat , The function of the method is if it is empty , Just throw the exception you defined , If not null, return the current object , In actual combat, all exceptions must be handled well , For code readability
Source code :
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
example : This is the actual combat source code
// A simple query
Member member = memberService.selectByPhone(request.getPhone());
Optional.ofNullable(member).orElseThrow(() -> new ServiceException(" No relevant data to query "));
边栏推荐
- Vnctf2022 open web gocalc0
- 使用net core 6 c# 的 NPOI 包,读取excel..xlsx单元格内的图片,并存储到指定服务器
- ArrayList 扩容详解,扩容原理[通俗易懂]
- DirectX repair tool v4.1 public beta! [easy to understand]
- 购物商城6.27待完成
- [zero basic IOT pwn] reproduce Netgear wnap320 rce
- 保证生产安全!广州要求危化品企业“不安全不生产、不变通”
- 一波三折,终于找到src漏洞挖掘的方法了【建议收藏】
- [15. Interval consolidation]
- Solidty智能合约开发-简易入门
猜你喜欢
643. Maximum average number of subarrays I
MIT团队使用图神经网络,加速无定形聚合物电解质筛选,促进下一代锂电池技术开发
Music player development example (can be set up)
111. Minimum depth of binary tree
互联网医院系统源码 医院小程序源码 智慧医院源码 在线问诊系统源码
[Verilog quick start of Niuke question series] ~ use functions to realize data size conversion
Build your own website (14)
[leetcode 324] swing sorting II thinking + sorting
Basic operations of SQL database
[getting started with Django] 13 page Association MySQL "multi" field table (check)
随机推荐
Microservice development steps (Nacos)
Zabbix API与PHP的配置
[dynamic programming] interval dp:p1005 matrix retrieval
Salesforce, Johns Hopkins, Columbia | progen2: exploring the boundaries of protein language models
[dynamic programming] p1004 grid access (four-dimensional DP template question)
一波三折,终于找到src漏洞挖掘的方法了【建议收藏】
tensorflow2-savedmodel convert to pb(frozen_graph)
Buuctf reinforcement question ezsql
30 Devops interview questions and answers
Vnctf2022 open web gocalc0
[leetcode 324] swing sorting II thinking + sorting
Generate random numbers (4-bit, 6-bit)
Filter &(登录拦截)
首届技术播客月开播在即
Day-02 database
Detailed explanation of ArrayList expansion, expansion principle [easy to understand]
cmake 基本使用过程
使用net core 6 c# 的 NPOI 包,讀取excel..xlsx單元格內的圖片,並存儲到指定服務器
opencv学习笔记五--文件扫描+OCR文字识别
Solid basic structure and array, private / public function, return value and modifier of function, event