4. Optional class learning added by jdk8

What is the use of the Optional class

  • The main problem to solve is the NullPointerException (NullPointerException)

How to deal with it?

  • The essence is a wrapper class containing optional values, which means that the Optional class can contain objects or be empty

Create Optional class

  • of()
  • If a null value is passed in as a parameter, an exception will be thrown
Optional<Student> opt = Optional.of(user);
  • ofNullable()
  • If the object is either null or non-null, you should use the ofNullable() method
Optional<Student> opt = Optional.ofNullable(user);
  • Access the value of the Optional object
  • get() method
Optional<Student> opt = Optional.ofNullable(student);
Student s = opt.get();
  • If the value exists, the isPresent() method will return true. Calling the get() method will return the object. Generally, you need to verify whether there is a value before using get, otherwise an error will be reported
public static void main(String[] args) {
 Student student = null;
 test(student);
}
public static void test(Student student){
 Optional<Student> opt = Optional.ofNullable(student);
 System.out.println(opt.isPresent());
}
  • Bottom or Else method
  • orElse() returns the value if there is a value, otherwise returns the value of the parameter passed to it
Student student1 = null;
Student student2 = new Student(2);
Student result = Optional.ofNullable(student1).orElse(student2);
System.out.println(result.getAge());
Student student = null;
int result = Optional.ofNullable(student).map(obj->obj.getAge()).orElse(4);
System.out.println(result);

 

Guess you like

Origin blog.csdn.net/qq_37790902/article/details/103309281