** JAVA8 new features -Optional class NPE problem solving **
** github details Reference : ** https: //github.com/java-open/jdk1.8-
API Introduction
1、Optional(T value), empty(), of(T value), ofNullable(T value)
of(T value),
- through of (T value) of the function constructed Optional object, when Value is empty, still reported NullPointerException.
- through of (T value) of the function constructed Optional objects, when the Value is not empty, the normal configuration Optional objects.
ofNullable(T value)
When the value is null, of (T value) will report a NullPointerException; ofNullable (T value) does not throw Exception, ofNullable (T value) directly back to a target EMPTY
orElse and orElseGet
When the equivalent value is null, a default value is given: When the user value is not null, the function will still perform the createUser orElse () method does not perform the function of the createUser orElseGet () method
public User createUser(){
User user = new User();
user.setName("zhangsan");
return user;
}
@Test public void test() {
User user = null;
user = Optional.ofNullable(user).orElse(createUser());
user = Optional.ofNullable(user).orElseGet(() -> createUser());
}
orElseThrow
When the value argument is null, direct throw out an exception
User user = null;
Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));
map(Function<? super T, ? extends U> mapper)和flatMap(Function<? super T, Optional> mapper)
Two operating functions do the conversion value.
In the specific usage for the map in terms of:
If the User structure is as below:
public class User {
private String name;
public String getName() {
return name;
} }
It takes time to name written as follows
String city = Optional.ofNullable(user).map(u-> u.getName()).get();
For flatMap terms:
If this is the User following structure
public class User {
private String name;
public Optional<String> getName() {
return Optional.ofNullable(name);
}
}
It takes time to name written as follows
String city = Optional.ofNullable(user).flatMap(u-> u.getName()).get();
isPresent()和ifPresent(Consumer<? super T> consumer)
isPresent that is, whether the value is a null value, and when the value ifPresent is not empty, do something.
As ifPresent (Consumer <? Super T> consumer), usage is very simple, as shown in FIG.
Optional.ofNullable(user).ifPresent(u->{
// TODO: do something
});
filter(Predicate<? super T> predicate)
Predicate method accepts a filter to filter the values contained Optional, if the value contained in the condition, then return to this or Optional; otherwise Optional.empty.
Usage is as follows
Optional<User> user1 = Optional.ofNullable(user).filter(u -> u.getName().length()<6);
As described above, if the length of the user name is less than 6, then returns. If it is greater than 6, and an EMPTY object is returned.
Use Case
In function method
Previously written
public String getCity(User user) throws Exception{ if(user!=null){
if(user.getAddress()!=null){
Address address = user.getAddress(); if(address.getCity()!=null){
return address.getCity();
}
}
}
throw new Excpetion("取值错误");
}
JAVA8 wording
public String getCity(User user) throws Exception{
return Optional.ofNullable(user)
.map(u-> u.getAddress())
.map(a->a.getCity())
.orElseThrow(()->new Exception("取指错误"));
}
Common method
package com.example.demo;
import com.example.demo.entity.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
/**
* Optional类测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestOptional {
/*
* Optional容器类的常用方法:
* of(T value):创建一个Optional实例
*/
@Test
public void test1() {
Optional<Employee> op = Optional.of(new Employee());
System.out.println(op.get());
}
/*
* empty():创建一个空的Optional实例
*/
@Test
public void test2() {
Optional<Employee> op = Optional.empty();
System.out.println(op.get());
}
/*
* ofNullable(T value):若T不为null,创建Optional实例,否则创建空实例
* isPresent():判断是否包含值
* orElse(T other):如果调用对象包含值,返回该值,否则返回other
* orElseGet(T other):如果调用对象包含值,返回该值,否则返回other获取的值
*/
@Test
public void test3() {
Optional<Employee> op = Optional.ofNullable(null);
// System.out.println(op.get());
System.out.println(op.isPresent());
Employee emp = op.orElse(new Employee("张三","公关"));
System.out.println(emp);
Employee emp1 = op.orElseGet(() -> new Employee());
System.out.println(emp1);
}
/*
* map(Function mapper):如果有值对其处理,并返回处理后的Optional,否则返回Optional.empty()
* flatMap(Function mapper):与map类似,要求返回值必须是Optional
*/
@Test
public void test4() {
Optional<Employee> op = Optional.ofNullable(new Employee("张三", "出台"));
Optional<String> str = op.map((e) -> e.getName());
System.out.println(str.get());
Optional<String> str1 = op.flatMap((e) -> Optional.of(e.getName()));
System.out.println(str1.get());
}
}
Example Two
For example, in the main program
Previously written
if(user!=null){ dosomething(user); }
JAVA8 wording
Optional.ofNullable(user) .ifPresent(u->{ dosomething(u); });