Java.util.optional learning notes

Time:2019-11-27

Java.util.optional is a new class in Java 8. As a container class holding instances, it can help us write more elegant empty code, and it also provides some practical APIs. The official documents are here. Next, let’s learn through practice:

Three construction methods of optional

First, optional.of (object object object): the input parameter object cannot be empty, otherwise a null pointer exception will be thrown. If you check the optional source code, the objects.requirennonnull method will be called, which has a null judgment:

public static  T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

Second, optional.ofnnullable (object object): the input parameter object can be empty. If the object is not empty, an optional instance will be created. If the object is empty, an option object of static final will be returned. Note that there is no new option instance here, but an instance of static final empty. What’s more interesting here is the generic problem. For example, I need two ops The type of the functional object is string and integer respectively. The code is as follows:

Optional optionalStr = Optional.ofNullable(null);
Optional optionalInt = Optional.ofNullable(null);

How can different types ensure that the same object is returned? Directly look at the source code of ofnullable and find that the empty method will be called:

public static Optional empty() {
        @SuppressWarnings("unchecked")
        Optional t = (Optional) EMPTY;
        return t;
    }

It was implemented through forced conversion, and then look at the empty object:

private static final Optional> EMPTY = new Optional<>();

It is declared through “;

Third, optional. Empty(): This is the empty method used in the analysis of optional. Ofnullable, which directly returns an instance empty of static final;

The usage of the optional. Of () method is a bit like an assertion. When the object is empty, it represents some unacceptable business exception, which needs to be handled as early as possible, and the business refuses to execute. In this scenario, optional. Of can be used;

Next, let’s start fighting;

Object used in the example: Student

Student is a common bean with three fields and corresponding get & Set Methods

package com.bolingcavalry;

/**
 * @author willzhao
 * @version V1.0
 *@ Description: a common bean
 * @email [email protected]
 *@ date 2017 / 8 / 26 11:23 PM
 */
public class Student {
    private int id;

    private String name;

    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

Usage of optional.ofnullable

Here is an example of the most commonly used option.ofnullable. We plan to get the student object from other systems according to the name. If the object is empty, we will return the default object. First, let’s see how we usually write when we don’t use option. The following code shows the standard if & else judgment:

private Student queryById(int id){
        //Todo here simulates querying from the database
        return null;
    }

    public Student getStudent(int id){
        Student student = queryById(id));

        //If it is empty, the default object will be returned
        return student==null ? DEFAULT : student;
    }

After using optional, as shown below, you don’t need to judge null to avoid null pointer exception:

private Student queryById(int id){
        //Todo here simulates querying from the database
        return null;
    }
    
    public Student getStudent(int id){
        Optional optional = Optional.ofNullable(queryById(id));

        //If it is empty, the default object will be returned
        return optional.orElse(DEFAULT);
    }

The orelse method can specify a return object when the value is empty. If the object needs to be obtained by calling a method (for example, if we can’t get the default object, we need to get it through the getdefault() method), the orelseget method is required to achieve the purpose, as follows:

private Student queryById(int id){
    //Todo here simulates querying from the database
    return null;
}

private Student getDefault(){
    return DEFAULT;
}

public Student getStudent(int id){
    Optional optional = Optional.ofNullable(queryById(id));

    //If it is empty, the default object will be returned
    return optional.orElseGet(() -> getDefault());
}

Optional map method

If our requirement is that the student object is not empty, it will return the upper case of name. If the student object is empty, it will return “invalid”. When there is no optional, it is written as follows. In addition to checking whether the student variable is empty, it is also necessary to check whether the name is empty:

private Student queryById(int id){
        //Todo here simulates querying from the database
        return null;
}

public String getStudentUpperName(int id){
    Student student = queryById(id);
    if(student!=null && student.getName()!=null){
        return student.getName().toUpperCase();
    }

    return "invalid";
}

With optional, you can write as follows:

private Student queryById(int id){
    //Todo here simulates querying from the database
    return null;
}

public String getStudentUpperName(int id){
    Optional optional = Optional.ofNullable(queryById(id));

    return optional.map(student -> student.getName())
                   .map(name -> name.toUpperCase())
                   .orElse("invalid");
}

As you can see from the above code, map can convert one optional object to another, and the first time is to convert optionalConverted to optional, the second time is optionalTurned into another optional, but this time the string is capitalized;

The source code of this actual battle has been uploaded to GIT. The address is[email protected]:zq2599/blog_demos.git, there are several projects in it. This time, the optionaldemo is used, as shown in the red box below:

这里写图片描述

The above is the basic usage of optional. The use of optional is a challenge to the previous empty writing method, but you can try to get used to this simple and elegant tool;

Welcome to my public address.

在这里插入图片描述