As a programmer, you must have encountered NullPointerException, which is inevitable for new comers or experienced people in the Jianghu, but it is so powerless. In order to solve it, you can only judge a value before using it. However, this will make the code become bloated. Fortunately, jdk8 introduces optional to deal with the problem of null, so we can no longer care too much about null.

Show the writing method before jdk8

 // First before jdk8
 Long id = 0L;
 User user = getUserById(id);
 if (user != null) {
     String name = user.getName();
     System.out.println("name=" + name);

If you don’t make a null judgment on the user obtained by the method, it’s easy to get a null pointer exception when you get its properties.

JDK 8 writing

 User userById = Optional.ofNullable(getUserById(id)).orElse(new User());
 String name = userById.getName();
 System.out.println("new name=" + name);

This writing method avoids empty judgment, and the code is very simple

Here’s how to use optional

1. First, construct of, of nullable, empty

//Empty builds an empty optional object
 Optional empty = Optional.empty();
 //Of constructs the user's optional object. The user object is not empty. If it is empty, NullPointerException will be reported during construction
 User user = new User();
 Optional userOptional = Optional.of(user);
 //Ofnull constructs an optional object. If the internal user is empty, an empty optional object is built
 Optional userOptionalOfNull = Optional.ofNullable(user);
 Optional objectOptional = Optional.of(null);
 Exception in thread "main" java.lang.NullPointerException
     at java.util.Objects.requireNonNull(Objects.java:203)
     at java.util.Optional.(Optional.java:96)
     at java.util.Optional.of(Optional.java:108)
     at com.zbb.jdk.jdk8Test.optional.OptionalOfTest.main(OptionalOfTest.java:32)

Look at the source code of ofnullable method

2. Get ifpresent, get, ispresent

Optional userOptional = Optional.ofNullable(getUserById(id));
 //Ispresent determines whether the optional object exists. If it exists, it returns true. Otherwise, it returns false
     //Judged to exist
     //Get if there is a value in the created optional, this value will be returned. Otherwise, NoSuchElementException will be thrown
     User user = userOptional.get();
     System.out.println("name" + user.getName());
 //If the value in the created optional exists, the method call will be executed, otherwise nothing will be done
 //The parameter of ifpresent method is a functional interface, which has no return value and can be directly expressed with lambda expression
 userOptional.ifPresent(user -> System.out.println("name=" + user.getName()));

The initial example can also be modified by ispresent, but this is not different from the original void determination, only the method is different, the essence is not different, so it is not recommended. Look at the source code of these methods

3. Get orelse, orelseget, orelsethrow

Optional userOptional = Optional.ofNullable(getUserById(id));
 //Orelse returns a value if optional has a value, and a default value if not
 //The default value is a class we created
 User user = userOptional.orElse(new User("xiaohong", "123456789"));
 System.out.println("name=" + user.getName()); // name=xiaohong
 //Orelseget if optional has a value, it returns the value; if not, it executes a supplier interface to return the generated value
 User userOrElseGet = userOptional.orElseGet(() -> new User("xiaohongGet", "123456789"));
 System.out.println("name=" + userOrElseGet.getName()); //name=xiaohongGet
 //Orelsethrow returns a value if optional has a value, or an exception generated by the specified supplier interface if not
 User userelsethrow = useroptional.orelsethrow (() - > new exception ("useroptional is empty! ())
 //An exception thrown when empty
 Exception in thread "main" java.lang.exception: useroptional is empty!
     at com.zbb.jdk.jdk8Test.optional.OptionalOrElse.lambda$main$1(OptionalOrElse.java:29)
     at java.util.Optional.orElseThrow(Optional.java:290)
     at com.zbb.jdk.jdk8Test.optional.OptionalOrElse.main(OptionalOrElse.java:29)

Look at the source code

Or else throw

4. Filter

Optional userOptional = Optional.ofNullable(new User("xiao", "123456"));
 //If the value in optional meets the condition, the optional object will be returned, otherwise the empty optional object will be returned
 User user = useroptional. Filter (U - > name. Equals (u.getname())). Orelse (new user ("not satisfied", ""));
 System.out.println("name=" + user.getName()); //name=xiao

5. Convert map, flatmap

Optional optional = Optional.ofNullable("zhang,san");
 //Execute funciton function when map optional object exists
 //You can return any type of value
 //The function interface modifies the value in the optional object and returns the modified value
 Optional optionalMap = optional.map(s -> s.split(",")); //Optional[[Ljava.lang.String;@19dfb72a]
 //Lambda expression return value in flatmap method must be an optionl instance
 Optional optionalFlatMap = optional.flatMap(s -> Optional.of("lisi"));//Optional[lisi]

As you can see from the source code, map and flatmap are function function calls provided to return an optional value if the value in optional exists. No
An empty optional object is returned.

The biggest difference is that after the map function is executed, any type of data will be used. After the call, the map will wrap the result with optional. While flatmap is an optional instance after the execution, flatmap will not encapsulate the result with optional.