当前位置:网站首页>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 "));
边栏推荐
- Guess lantern riddles, not programmers still can't understand?
- [getting started with Django] 13 page Association MySQL "multi" field table (check)
- MongoDB第二話 -- MongoDB高可用集群實現
- 【14. 区间和(离散化)】
- ArrayList 扩容详解,扩容原理[通俗易懂]
- The data in the database table recursively forms a closed-loop data. How can we get these data
- 官宣:Apache Doris 顺利毕业,成为 ASF 顶级项目!
- openssl客户端编程:一个不起眼的函数导致的SSL会话失败问题
- 这3款在线PS工具,得试试
- JVM second conversation -- JVM memory model and garbage collection
猜你喜欢

Minimum spanning tree and bipartite graph in graph theory (acwing template)

一波三折,终于找到src漏洞挖掘的方法了【建议收藏】

IDEA全局搜索快捷键(ctrl+shift+F)失效修复

竣达技术丨多台精密空调微信云监控方案

Filter &(登录拦截)

Cannot link redis when redis is enabled

定了!2022海南二级造价工程师考试时间确定!报名通道已开启!

Details of appium key knowledge

Basic operations of SQL database

JVM performance tuning and practical basic theory part II
随机推荐
JVM second conversation -- JVM memory model and garbage collection
Research Report on the development trend and competitive strategy of the global commercial glassware industry
Build MySQL master-slave server under Ubuntu 14.04
Research Report on the development trend and competitive strategy of the global camera filter bracket industry
What are the books that have greatly improved the thinking and ability of programming?
【锁】Redis锁 处理并发 原子性
Research Report on development trend and competitive strategy of global consumer glassware industry
[14. Interval sum (discretization)]
竣达技术丨多台精密空调微信云监控方案
Pat 1121 damn single (25 points) set
Mongodb second call -- implementation of mongodb high availability cluster
2022-2-15 learning the imitation Niuke project - Section 3 post details
Buuctf reinforcement question ezsql
从零开发小程序和公众号【第三期】
Mongodb second talk - - mongodb High available Cluster Implementation
Sqlachemy common operations
[Verilog quick start of Niuke series] ~ multi function data processor, calculate the difference between two numbers, use generate... For statement to simplify the code, and use sub modules to realize
Opencv mat class
问题随记 —— Oracle 11g 卸载
What are the requirements for NPDP product manager international certification registration?