Introduction to the
In order to simplify the null pointer exception judgment code writing
Under normal circumstances
if(object ! =null){
object2 = object.getMethod();// This may be null
if(obejct2 ! =null){
o3 = object2.method();// It may be null again
if. }}Copy the code
It was introduced to simplify writing and accommodate Lambda expressionsOptional
class
Let’s cut the details and get right to it
Source code cannot be lost
Elements of perceived
Instantiate Optional’s methods
empty()
// Create an empty objectof(T value)
// Create a non-empty objectofNullable(T value)
/ / create an emptyorNot empty object
An empty object is also an object
Return Optional’s method
filter(Predicate<? super T> predicate)
Return this or an empty object based on Predicatemap(Function<? super T, ? extends U> mapper)
// Operate ona non-empty value and construct an Optional with it. Return the new OptionalflatMap(Function<? super T, Optional<U>> mapper
// Operate on non-empty this.value and return this
Method to get the member variable value
get()
// The classic get methodorElse(T other)
// If value is null, other is returned.orElseGet(Supplier<? extends T> other)
// Return a non-null this.value, otherwise return the operated otherpublic <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
// Return a non-empty value, otherwise raise an exception
Functional approach
boolean isPresent()
// Check whether value is nullifPresent(Consumer<? super T> consumer)
// The operation is not null. Value Does not return a value
test
public class OptionalTest {
public static void main(String[] args) {
People people = new People("Kitty".18);
People people2 = new People("Google".30);
Optional<People> optional = Optional.of(people);// Wrap the object people
optional.ifPresent( p -> p.setAge(20));// If Optional is not empty, p is the value of the Optional member
System.out.println(optional.flatMap(p -> {
p.setName("Jane");
return Optional.of(p);//flatMap to return Optional
}).filter(p -> p.getAge() == 18).orElse(people2)); optional.ifPresent(System.out::println); }}Copy the code
explain
Note with optional
Optional is based on the value type
- The official explanation
Optional is the most basic use
- Not recommended
if(optional. IsPresent ()){all calls}Copy the code
- Recommend writing
Optional. IfPresent (using Lambda expressions for various SAO operations);Copy the code
- All the Optional methods have a non-null judgment, so feel free to use them
Optional is not serializable
- Therefore, it cannot be treated as a member variable of another class
- So it can’t be a method parameter, but it can be the return value