summary
- 1. The biggest highlight of JDK8 is the introduction of Optional class to solve NPE (NullPointerException)
- 2. The Alibaba development manual also recommends the use of the Optional class to prevent NPE
- 3. To sum up, solving NPE is the function of the Optional class and a highlight of JDK8
Optional Preview
- 1. Declaration of the Optional class
- 1) It is declared final, that is, it cannot be inherited
- 2) Use generic T, which specifies the type of object contained in option
public final class Optional<T>
- 2. Important properties of the Optional class
- 1) The value of the final type is the Optional containing object, where T is the type specified through the generic type when creating the Optional
- 2) The global static constant EMPTY calls the parameterless construction of the Optional class, where the representative value is set to null
private final T value; private static final Optional<?> EMPTY = new Optional<>();
- 3. Construction method of Optional class
- It can be seen that the two construction methods of Optional are declared as private, which means that the external world cannot create Optional objects through new, that is, they are generally used internally
private Optional() { this.value = null; } private Optional(T value) { this.value = Objects.requireNonNull(value); }
Optional - API
Methods | Params | Return | Purpose | Theory | Frequency |
---|---|---|---|---|---|
empty() | nothing | Optional<T> | Set the value of Optional to null | Forcibly convert the global static constant EMPTY to the corresponding T type Optional, and then return it | occasional |
of() | T type variable | Optional<T> | Create an Optional object containing value | Call the Optional parameterized constructor to assign the passed variable to value | often |
ofNullable() | T type variable | Optional<T> | Create an Optional object containing value | First judge whether value is empty If value is empty, directly call the empty method to return an empty Optional object If value is not empty, call the of method to return a non empty Optional object containing value | always |
get() | nothing | T type variable | Get value in Optional Note: generally, you need to call isPresent to judge that value is not empty | If the current value is empty, NoSuchElementException will be thrown Otherwise, return value directly | occasional |
isPresent | nothing | Boolean variable | Judge whether the value in Optional is not empty | Directly judge whether value is not empty | occasional |
ifPresent | Consumer consumer interface | nothing | Specify action for value in Optional | When value is not empty, specify action for value | usual |
filter | Predicate assertion interface | Optional<T> | Specify test for value in Optional | Call the Objects tool class to perform non null verification on the incoming assertion interface Call isPresent method. When value is empty, the current Optional object will be returned directly When value is not empty, specify test on value. If the assertion succeeds, the current Optional object will be returned. If the assertion fails, the empty object will be returned by calling the empty method | often |
map | Function function interface | Optional<U> | Specify apply for value in Optional | Call the Objects tool class to perform non null verification on the incoming functional interface Call the isPresent method. When value is empty, directly call the empty method to return an empty Optional object When value is not empty, specify apply for value, then call ofNullable method to encapsulate the result into new Optional. | usual |
flatMap | Function function interface | Optional<U> | Specify apply for value in Optional Similar to map, but it does not optionally repackage the results | Call the Objects tool class to judge that the incoming functional interface is not empty Call the isPresent method. When value is empty, directly call the empty method to return an empty Optional object When value is not empty, specify apply for value, then call Objects tool class to perform non null verification of results. | usual |
orElse | T type variable | T type variable | Returns the value in Optional. If value is empty, the passed variable is returned | Judge whether value in Optional is empty If value is not empty, value is returned If value is empty, the passed T-type variable is returned | usual |
orElseGet | Supplier Supply type interface | T type variable | Return the value in Optional. If value is empty, return the T-type variable produced by the Supplier | Judge whether value in Optional is not empty If value is not empty, value is returned If value is empty, a T-type variable produced through the Supplier's get method is returned | usual |
orElseThrow | Supplier Supply type interface | T type variable | Return the value in Optional. If value is empty, an exception message produced by the Supplier will be thrown | Judge whether value in Optional is not empty If value is not empty, value is returned If value is empty, an exception message will be generated through the Supplier's get method | occasional |
Optional delve - Demo
Note: only the frequently used methods are studied here, and other methods are not difficult to understand.
- Generally, the ofNullable method is used to create an Optional, because it can receive both non Null and Null
- Generally, the map method is used to replace the getter operation after non empty judgment
- Generally, the last value is obtained through the orElse method, in which null is generally passed in
package com.gezq.optionaldemos; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Optional; /** * Desc: Simple test Optional * * @author gezq0714 * @version MyDemo:1.0.0 * @email ge051799qi@163.com * @date 2021/10/1 - 20:49 * @since MyDemo:1.0.0 */ public class Demo { public static void main(String[] args) { // Suppose User is an object queried in the database, and what we want to get is skillName User user = new User("gezq", "123456", new Skill("sing", Optional.of("you like sing"))); // General operation String skillName1 = null; // 1. Judge user is not empty if (user != null) { // 2. Get skill final Skill skill = user.getSkill(); // 3. Judge skill is not empty if (skill != null) { // 4. Get skillName skillName1 = skill.getSkillName(); } } // Use Optional -- use map to get the value of common attributes final String skillName2 = Optional.ofNullable(user).map(User::getSkill).map(Skill::getSkillName).orElse(null); // Use Optional -- use flatMap to get the value of the attribute wrapped by Optional final String skillIntroduction = Optional.ofNullable(user).map(User::getSkill).flatMap(Skill::getIntroduction).orElse(null); System.out.println("General operation acquisition skillName: " + skillName1); System.out.println("use Optional obtain skillName: " + skillName2); System.out.println("use Optional obtain skillIntroduction: " + skillIntroduction); /* The output results are as follows: General operation: get skillName: sing Use Optional to get skillName: sing Use Optional to get skillIntroduction: you like sing */ } } @AllArgsConstructor @NoArgsConstructor @Data class User { private String username; private String password; private Skill skill; } @AllArgsConstructor @NoArgsConstructor @Data class Skill { private String skillName; private Optional<String> introduction; }