Initialization
Optional provides three initialization methods:
@SpringBootTest public class OptionalTest {<!-- --> @Test public void testOptional() {<!-- --> Optional.empty(); Optional.ofNullable(null); Optional.of(null); } }
empty returns an empty Optional object.
of will report an error when encountering null, but the purpose of using Optional is to prevent null pointers, so ofNullable is generally used more often.
ifPresent
ifPresent–If exists then xxx
public void testOptional() {<!-- --> Student student = new Student(); student.setName("feng"); student.setAge(18); Optional.of(student); // Common practice if(student != null){<!-- --> System.out.println(student.getName()); } // Optional common usage Optional<Student> optional = Optional.ofNullable(student); if(optional.isPresent()){<!-- --> Student student1 = optional.get(); System.out.println(student1.getName()); } // Correct usage optional.map(new Function<Student, String>() {<!-- --> @Override public String apply(Student student) {<!-- --> return student.getName(); } }).ifPresent(System.out::println); // Simplify optional.map(Student::getName).ifPresent(System.out::println); }
orElse and orElseGet
If there is no object, a method that creates the object is called.
orElse is similar to Hungry style. If the current object is not empty, the current object is used. If it is empty, the method is called to create a new object.
orElseGet is similar to the lazy style. It will be called only when the current object is empty. OrElseGet is usually used more often.
The current object is not empty:
public void testOptional() {<!-- --> Student student = new Student(); student.setName("feng"); student.setAge(18); Optional<Student> optional = Optional.ofNullable(student); Student student1 = optional.orElse(createStudent()); // orElseGet receives a Suppilier, an anonymous inner class, and calls the get method to process the logic Student student2 = optional.orElseGet(new Supplier<Student>() {<!-- --> @Override public Student get() {<!-- --> return createStudent(); } }); } private Student createStudent(){<!-- --> System.out.println("create student"); return new Student(); }
The current object is empty:
public void testOptional() {<!-- --> Student student = null; Optional<Student> optional = Optional.ofNullable(student); Student student1 = optional.orElse(createStudent()); // orElseGet receives a Suppilier, an anonymous inner class, and calls the get method to process the logic Student student2 = optional.orElseGet(new Supplier<Student>() {<!-- --> @Override public Student get() {<!-- --> return createStudent(); } }); } private Student createStudent(){<!-- --> System.out.println("create student"); return new Student(); }
Filter
public void testOptional() {<!-- --> Student student = new Student(); student.setName("feng"); student.setAge(18); Optional<Student> optional = Optional.ofNullable(student); optional.filter(student1 -> student1.getAge() > 1).ifPresent(student1 -> System.out.println(student1.getAge())); }
map and flatMap
Optional
is a container class in Java used to handle values that may or may not contain values. Optional
provides several methods to operate on these values, including map
and flatMap
.
Optional.map
:- The
map
method is used to convert or operate on theOptional
if it contains a value. - If the
Optional
contains a value,map
will pass the value to the provided function and return a newOptional
containing the result of the conversion. - If
Optional
is empty,map
does not perform any operation and directly returns an emptyOptional
. - The signature of
map
is as follows:Optional map(Function super T, ? extends U> mapper)
- The
Optional<String> optional = Optional.of("Hello"); Optional<Integer> lengthOptional = optional.map(s -> s.length());
In the above example, optional
contains a string value “Hello”, and the map
method calculates the length of the string and returns a new Optional
Contains the result of the calculation, which is an integer.
Optional.flatMap
:- The
flatMap
method is used to perform a flat map if theOptional
contains a value, and it expects the passed-in function to return anotherOptional
. - If
Optional
contains a value,flatMap
passes that value to the provided function, which returns anOptional
and thenflatMap
Return this newOptional
. - If
Optional
is empty,flatMap
does not perform any operation and directly returns an emptyOptional
. - The signature of
flatMap
is as follows:Optional flatMap(Function super T, Optional> mapper)
- The
Optional<String> optional = Optional.of("Hello"); Optional<Integer> lengthOptional = optional.flatMap(s -> Optional.of(s.length()));
In the above example, optional
contains a string value “Hello”, and the flatMap
method calculates the length of the string and returns a new Optional
Contains the result of the calculation, which is an integer. Note that the flatMap
function returns Optional
, not Optional
, because flatMap
will automatically flatten the nested Optional
into a single layer.
Summarize:
map
is used to convert the contained value and return a newOptional
.flatMap
is used to flat map the contained value and return a newOptional
, which is usually used to solve the problem of nestedOptional
.
Overall use
//Normal public void before8(List<Student> Students) {<!-- --> for (Student student:Students) {<!-- --> if (student != null){<!-- --> if (student.getAge() > 18){<!-- --> Integer score = student.getScore(); if (score != null & amp; & amp; score > 80){<!-- --> System.out.println(student.getName()); } } } } } //1 public void after8(List<Student> students) {<!-- --> students.stream() .filter(Objects::nonNull) // Filter out empty student objects .filter(student -> student.getAge() > 18) // Filter by age .map(Student::getScore) //Map to score .filter(score -> score != null & amp; & amp; score > 80) // Filter by score .map(Student::getName) //Map to name .ifPresent(System.out::println); //Print if name exists } public void after8(List<Student> Students) {<!-- --> for (Student student:Students) {<!-- --> Optional<Student> studentOptional = Optional.of(student); \t\t\t // 2 Integer sorce = studentOptional .filter(s -> s.getAge() > 18) .map(Student::getScore) .orElse(0);//.orElse(0) returns a default value to prevent null pointer control if (sorce > 80){<!-- --> System.out.println(student.getName()); } // 3 String name = studentOptional .filter(s -> s.getAge() >= 18) .filter(s -> s.getScore() > 80) .map(Student::getName) .orElse("wu");//.orElse(0) returns a default value to prevent null pointer control System.out.println(name); } }