Optional class of JDK 8

What is the Optional class

NPE (Null Pointer Exception) has always been our most troublesome problem, and it is also the most easily overlooked place. NPE is often the most common cause of failure of Java applications. In daily R&D work, various variables and sets are often dealt with, but in the process of use, it is often necessary to make empty judgments, otherwise NPE will appear.

The Optional class is actually a container: it can store the value of type T, or just store null. The introduction of the Optional class is a good solution to the null pointer exception. Optional provides many useful methods so that we don't need to explicitly check for null values. Try to avoid directly calling the get() and isPresent() methods of the Optional object in the program, and avoid using the Optional type to declare the attributes of the entity class.

Optional.of(T t): Create an Optional instance
Optional.empty(): Create an empty Optional instance
Optional.ofNullable(T t): If t is not null, create an Optional instance, otherwise create an empty instance
isPresent(): Judge whether it contains a value
orElse(T t): If the calling object contains a value, return the value, otherwise return t
orElseGet(Supplier s): If the calling object contains a value, return the value, otherwise return the value obtained by s
map(Function f) : If there is a value to process it, and return the processed Optional, otherwise return Optional.empty()
flatMap(Function mapper): Similar to map, the return value must be Optional

How to use the Optional class

The following code compares the code after using the Optional class in two common scenarios. It can be seen that the code is much more concise.

The first scenario: Determine whether it is empty

package com.java.bitmap;
 
import java.util.Optional;
 
public class OptionalDemo {
 
    public static void main(String[] args) {
        String name="kerry";
        // common way
        if (name!=null&&name.length()!=0){
            System.out.println(name.length());
        }
        //use optional way
        System.out.println(Optional.ofNullable(name).orElse("").length());
 
 
    }
}

The second scenario: traversing the list object

 public static void listIterator(List<Integer> list){
        // common way
        if (list!=null&&list.size()!=0){
            for (Integer tmp:list) {
                System.out.println(tmp);
            }
        }
        //use optional way
        Optional.ofNullable(list).orElse(new ArrayList<>()).forEach(tmp->{System.out.println(tmp);});
    }

The third scene:

public User getUser(User user) throws Exception{
    if(user!=null){
        String name = user.getName();
        if("zhangsan".equals(name)){
            return user;
        }
    }else{
        user = new User();
        user.setName("zhangsan");
        return user;
    }
}

public User getUser(User user) {
    return Optional.ofNullable(user)
                   .filter(u->"zhangsan".equals(u.getName()))
                   .orElseGet(()-> {
                        User user1 = new User();
                        user1.setName("zhangsan");
                        return user1;
                   });
}

orElseGet is similar to orElse, both of which can be returned with a custom type. The former supports lamaba expressions.
Original link: https://blog.csdn.net/hanruikai/article/details/113995276

Guess you like

Origin blog.csdn.net/weixin_40648700/article/details/114137416