简介
Optional是Java引入的类,用来解决空指针问题。并可以增加代码的整洁性。先看看源码介绍:
A container object which may or may not contain a non-null value. If a value is present, isPresent() returns true and get() returns the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (returns a default value if no value is present) and ifPresent() (performs an action if a value is present).
This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.
简单来说:一个包含了null或非null对象的容器,若对象存在,则调用 isPresent() 返回true,调用get()返回当前对象。还提供了一些额外的方法来对包含的对象的处理。后续会介绍。另外就是这个是基于对象的类,避免使用对象敏感的操作,如equal或hash code等。
使用
Method Summary
(从源码中复制,仅供参考学习)
Modifier and Type | Method | Description |
---|---|---|
static Optional | empty() | Returns an empty Optional instance. |
boolean | equals(Object obj) | Indicates whether some other object is “equal to” this Optional . |
Optional | filter(Predicate predicate) | If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional . |
Optional | flatMap(Function> mapper) | If a value is present, returns the result of applying the given Optional -bearing mapping function to the value, otherwise returns an empty Optional . |
T | get() | If a value is present, returns the value, otherwise throws NoSuchElementException . |
int | hashCode() | Returns the hash code of the value, if present, otherwise 0 (zero) if no value is present. |
void | ifPresent(Consumer action) | If a value is present, performs the given action with the value, otherwise does nothing. |
void | ifPresentOrElse(Consumer action,Runnable emptyAction) | If a value is present, performs the given action with the value, otherwise performs the given empty-based action. |
boolean | isPresent() | If a value is present, returns true , otherwise false . |
Optional | map(Function mapper) | If a value is present, returns an Optional describing (as if by ofNullable(T) ) the result of applying the given mapping function to the value, otherwise returns an empty Optional . |
static Optional | of(T value) | Returns an Optional describing the given non-null value. |
static Optional | ofNullable(T value) | Returns an Optional describing the given value, if non-null , otherwise returns an empty Optional . |
Optional | or(Supplier> supplier) | If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function. |
T | orElse(T other) | If a value is present, returns the value, otherwise returns other . |
T | orElseGet(Supplier supplier) | If a value is present, returns the value, otherwise returns the result produced by the supplying function. |
T | orElseThrow(Supplier exceptionSupplier) | If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function. |
Stream | stream() | If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream . |
String | toString() | Returns a non-empty string representation of this Optional suitable for debugging. |
使用
ofNullable, orElse
Integer integer1 = 1;
Integer integer2 = null;
Optional<Integer> optional1 = Optional.ofNullable(integer1);
Optional<Integer> optional2 = Optional.ofNullable(integer2);
Integer test = optional2.orElse(3);
System.out.println("optional1.get() = " + optional1.get());
System.out.println("optional2.get() = " + test);
//result:
//optional1.get() = 1
//optional2.get() = 3
基础使用如上方源码,可对对象做一个基本判空处理,若果为空,可赋予一个默认值;不为空,则返回当前值。
ArrayList<Integer> arrayList = new ArrayList<>();
optional1.ifPresent(arrayList::add);
System.out.println("arrayList.get(0) = " + arrayList.get(1));
判空后会可以对数据处理操作,此处是若integer不为空的话,arrayList将其add进去,arrayList::add是lambda表达式,也是Java 8引入的,感兴趣的可以学习一下。
filter
Optional<Integer> optional3 = optional1.filter(val -> val > 2);
Optional<Integer> optional4 = optional1.filter(val -> val < 2);
System.out.println("optional3.get() = " + optional3);
System.out.println("optional4.get() = " + optional4.get());
//result
//optional3.get() = Optional.empty
//optional4.get() = 1
filter的方式用来做数据筛选,optional1包含的值是1,所以optional3.get()就会返回empty。
map, flatMap
class Student {
String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
class Teacher {
String userName;
public Optional<String> getUserName() {
return Optional.ofNullable(userName);
}
public void setUserName(String userName) {
this.userName = userName;
}
}
class School {
Student student;
Teacher teacher;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
Student student = new Student();
student.setUserName("student");
Teacher teacher = new Teacher();
teacher.setUserName("teacher");
School school = new School();
school.setStudent(student);
school.setTeacher(teacher);
Optional<School> optional5 = Optional.ofNullable(school);
String doubleName = optional5.map(School::getStudent).map(Student::getUserName).orElse("defalut");
String teacherName = Optional.of(teacher).flatMap(Teacher::getUserName).orElse("teacher");
System.out.println("doubleName = " + doubleName);
System.out.println("teacherName = " + teacherName);
创建了三个对象,School,Teacher,Student,optional5.map(School::getStudent).map(Student::getUserName).orElse("defalut");
看到这行代码,就能知道,以后不用担心空指针,而不断的判断null了,直接一层一层使用map,进行数据返回。那么flatMap和map有什么区别呢,看代码好像是一样的,区别在于map封装了optional的返回,而flatMap
没有,看一下teacher.getUserName()就可以看到:flatMap返回必须是optional,而map不用
public Optional<String> getUserName() {
return Optional.ofNullable(userName);
}
总结
Optional极大的减少了空指针的问题,并且简洁了代码,不用多层if,一直判断。好东西,请多用!