Introduction: To learn a new technology, we must learn with questions. Not only to figure out the origin and use of this technology, but also to figure out what benefits we have to learn this technology to knock on the code.

1. Why use Optional?

1.1 a scene

Xiao Ming encountered a problem when writing code in the company: to obtain the number of a student’s class, Xiao Ming had a brainwave and whizzed out:

String  code =  user.getMyClass(a).getClassroom(a).getCode(a);Copy the code

“But Ken will throw a null-pointer exception whenever any of these objects is null!” Thinking of this, Xiao Ming immediately made a modification:

if (null! = user) { MyClass myClass = user.getMyClass();if (null! = myClass) { Classroom classroom = myClass.getClassroom();if (null! = classroom) { String code = classroom.getCode(); }}}Copy the code

Xiao Ming looked at the code, which he thought was elegant, and laughed: “I am really very smart! Hey hey hey!”

“But why does this code look like a nesting doll? Is there a solution? “Xiao Ming fell into silence…

1.2 scenario 2

Ming’s colleague, Xiao Wang, taught himself Lambda last weekend, hoping to show off and show his real strength.

He had a problem getting the maximum age of students older than 21.

He thought for a moment and wrote the following code:

int maxAge = userList.stream().map(user -> user.getAge()).filter(age -> age > 21).mapToInt(Integer::intValue).max().getAsInt();
Copy the code

However, an error was reported when running:

Wang thought, must encounter a null pointer, that I change:

Stream<Integer> integerStream = userList.stream().map(user -> user.getAge()).filter(age -> age > 21);
if(null! = integerStream){int maxAge = integerStream.mapToInt(Integer::intValue).max().getAsInt();
    System.out.println(maxAge);
}
Copy the code

Then run:

Xiao Wang was dumbfounded…

1.3 know the optional

Xiao Ming and Xiao Wang were surprised because they did not use optional options flexibly.

Optional, a new feature introduced in Java 8, acts like a container that can contain objects or be null, thereby avoiding null Pointers.

2. Optional

2.1 of( )

Puts a specific value inside the Optional container and returns an Optional object. However, this particular value cannot be null, otherwise a NullPointerException will be thrown.

For example:

Optional<Integer> number1 = Optional.of(123);
System.out.println(number1);
System.out.println(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "); Optional<Integer> number2 = Optional.of(null);
System.out.println(number2);
Copy the code

Running results:

2.2 ofNullable( )

Place an optional value in the Optional container and return an Optional object, which can be null. If the value is null, an empty Optional object is returned.

For example:

Optional<String> number1 = Optional.ofNullable(" Bless the motherland72Happy anniversary "); System.out.println(number1);
System.out.println(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "); Optional<Integer> number2 = Optional.ofNullable(null);
System.out.println(number2);
Copy the code

Running results:

2.3 isPresent( )

Calling isPresent() returns false if the returned object has no value, true otherwise.

For example:

List<User> userList = Stream.of(new User("Zhang".18), new User("Bill".21)).collect(Collectors.toList());
boolean present = userList.stream().filter(user -> user.getAge() > 21).findFirst().isPresent();
System.out.println(present);
Copy the code

Running results:

2.4 the get ()

Calling this method returns if it has a value, or an error if it has no value.

For example:

List<User> userList = Stream.of(new User(" zhang SAN ",18), new User(" li Si ",21)).collect(Collectors.toList());
User user1 = userList.stream(a).filter(user -> user.getAge(a) >18).findFirst(a).get(a); System.out.println(user1);
System.out.println(" -- -- -- -- -- -- -- -- -- -- "); User user2 = userList.stream(a).filter(user -> user.getAge(a) >21).findFirst(a).get(a); System.out.println(user2);
Copy the code

Running results:

2.5 ifPresent( )

Call this method if it has a value, otherwise not

For example:

List<User> userList = Stream.of(new User(" zhang SAN ",18), new User(" li Si ",21)).collect(Collectors.toList());
userList.stream(a).filter(user -> user.getAge(a) >18).findFirst(a).ifPresent(user -> {
    System.out.println(user);
});
System.out.println(" -- -- -- -- -- -- -- -- -- -- "); userList.stream(a).filter(user -> user.getAge(a) >21).findFirst(a).ifPresent(user -> {
    System.out.println(11111111);
    System.out.println(user);
});
Copy the code

Running results:

2.6 orElse( )

Returns a value, otherwise a given default value.

For example:

List<Integer> nums = Stream.of(11.17.34.78).collect(Collectors.toList());
Integer num1 = nums.stream(a).filter(w -> w > 11).mapToInt(Integer::intValue).max().orElse(99);
System.out.println(num1);
System.out.println(" -- -- -- -- -- -- -- -- "); Integer num2 = nums.stream(a).filter(w -> w > 78).findFirst(a).orElse(99);
System.out.println(num2);
Copy the code

Running results:

2.7 orElseGet( )

Returns if there is a value, otherwise a method returns a given default value.

For example:

public static int getNum(a){
    return 12;
}
public static void main(String[] args) {
  List<Integer> nums = Stream.of(11.17.34.78).collect(Collectors.toList());
  Integer num1 = nums.stream().filter(w -> w > 11).mapToInt(Integer::intValue).max().orElse(99);
  System.out.println(num1);
  System.out.println("-- -- -- -- -- -- -- --");
  Integer num2 = nums.stream().filter(w -> w > 78).findFirst().orElseGet(()->2);
  System.out.println(num2);
  Integer num3 = nums.stream().filter(w -> w > 78).findFirst().orElseGet(()->getNum());
  System.out.println("-- -- -- -- -- -- -- --");
  System.out.println(num3);
}
Copy the code

Running results:

3. Optional case

User user1= null;
String code1 = Optional.ofNullable(user1).map(w -> w.getMyClass(a).getClassroom(a).getCode()).orElse(" No code found "); System.out.println(code1);
System.out.println(" -- -- -- -- -- -- -- -- -- "); User user2 = new User(" user2 ",19, new MyClass(new Classroom("13")));
String code2 = Optional.ofNullable(user2).map(w -> w.getMyClass(a).getClassroom(a).getCode()).orElse(" No code found "); System.out.println(code2);
Copy the code

Running results:

4. To summarize

    1. When null Pointers are possible, place the result in optional.ofnullable () and use orElse() to set the default value.
    1. Learn to work with lambda expressions.