当前位置:网站首页>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 "));
边栏推荐
- How to view the state-owned enterprises have unloaded Microsoft office and switched to Kingsoft WPS?
- What are the books that have greatly improved the thinking and ability of programming?
- 对于编程思想和能力有重大提升的书有哪些?
- What data capabilities do data product managers need to master?
- Some thoughts on software testing
- Rearrangement of overloaded operators
- 【14. 区间和(离散化)】
- opencv学习笔记六--图像拼接
- Build MySQL master-slave server under Ubuntu 14.04
- QT capture interface is displayed as picture or label
猜你喜欢

Word2vec yyds dry goods inventory

Blog recommendation | in depth study of message segmentation in pulsar
![[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
![[14. Interval sum (discretization)]](/img/e5/8b29aca7068a6385e8ce90c2742c37.png)
[14. Interval sum (discretization)]

opencv学习笔记四--银行卡号识别

对于编程思想和能力有重大提升的书有哪些?

手把手带你入门 API 开发

Chapter 4 of getting started with MySQL: creation, modification and deletion of data tables
![[leetcode 324] swing sorting II thinking + sorting](/img/cb/26d89e1a1f548b75a5ef9f29eebeee.png)
[leetcode 324] swing sorting II thinking + sorting

C#学习笔记(5)类和继承
随机推荐
Detailed explanation of ArrayList expansion, expansion principle [easy to understand]
Solid basic structure and array, private / public function, return value and modifier of function, event
TypeScript: let
从零开发小程序和公众号【第三期】
JVM第一话 -- JVM入门详解以及运行时数据区分析
APK签名原理
opencv学习笔记四--银行卡号识别
问题随记 —— Oracle 11g 卸载
Build your own website (14)
Research Report on the development trend and competitive strategy of the global commercial glassware industry
手把手带你入门 API 开发
Mongodb second call -- implementation of mongodb high availability cluster
Minimum spanning tree and bipartite graph in graph theory (acwing template)
Yyds dry goods inventory hcie security day13: firewall dual machine hot standby experiment (I) firewall direct deployment, uplink and downlink connection switches
Buuctf reinforcement question ezsql
Generate random numbers (4-bit, 6-bit)
openssl客户端编程:一个不起眼的函数导致的SSL会话失败问题
写在Doris毕业后的第一天
深度分析数据在内存中的存储形式
solidty-基础篇-结构体和数组,私有 / 公共函数,函数的返回值和修饰符,事件