当前位置:网站首页>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
OptionalTo 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 "));
边栏推荐
- Detailed explanation of ArrayList expansion, expansion principle [easy to understand]
- Fundamentals of C language
- JVM第一话 -- JVM入门详解以及运行时数据区分析
- Opencv mat class
- Demand prioritization method based on value quantification
- Rearrangement of overloaded operators
- 111. Minimum depth of binary tree
- What is the relationship between network speed, broadband, bandwidth and traffic?
- Use the npoi package of net core 6 C to read excel Pictures in xlsx cells and stored to the specified server
- MongoDB第二话 -- MongoDB高可用集群实现
猜你喜欢

Vnctf2022 open web gocalc0

The State Administration of Chia Tai market supervision, the national development and Reform Commission and the China Securities Regulatory Commission jointly reminded and warned some iron ores

Buuctf reinforcement question ezsql

Blog recommendation | in depth study of message segmentation in pulsar

Don't want to knock the code? Here comes the chance

Salesforce, Johns Hopkins, Columbia | progen2: exploring the boundaries of protein language models
![[dynamic programming] p1004 grid access (four-dimensional DP template question)](/img/3a/3b82a4d9dcc25a3c9bf26b6089022f.jpg)
[dynamic programming] p1004 grid access (four-dimensional DP template question)
![[leetcode 324] swing sorting II thinking + sorting](/img/cb/26d89e1a1f548b75a5ef9f29eebeee.png)
[leetcode 324] swing sorting II thinking + sorting

【15. 区间合并】
![[Verilog quick start of Niuke question series] ~ use functions to realize data size conversion](/img/e1/d35e1d382e0e945849010941b219d3.png)
[Verilog quick start of Niuke question series] ~ use functions to realize data size conversion
随机推荐
三十之前一定要明白的职场潜规则
Microservice development steps (Nacos)
【LeetCode】16、最接近的三数之和
Apk signature principle
Research Report on the development trend and competitive strategy of the global display filter industry
数字化转型:数据可视化赋能销售管理
The State Administration of Chia Tai market supervision, the national development and Reform Commission and the China Securities Regulatory Commission jointly reminded and warned some iron ores
solidty-基础篇-结构体和数组,私有 / 公共函数,函数的返回值和修饰符,事件
C learning notes (5) class and inheritance
Quelle valeur le pdnp peut - il apporter aux gestionnaires de produits? Vous savez tout?
期末琐碎知识点再整理
The data in the database table recursively forms a closed-loop data. How can we get these data
Advanced C language
Research Report on the development trend and competitive strategy of the global camera filter bracket industry
Don't want to knock the code? Here comes the chance
2022-2-15 learning xiangniuke project - Section 4 business management
Pat 1121 damn single (25 points) set
Redis installation and setting up SSDB master-slave environment under Ubuntu 14.04
solidty-基础篇-基础语法和定义函数
JVM performance tuning and practical basic theory part II