[Java Basics] Use Optional to solve the problem of judging that Null is empty

1. Background

At the beginning of the article, let's talk about the NPE problem. The NPE problem is the NullPointerException that we often encounter in development.

Review the previous handling of null:

package com.biyu.study.optional;

public class OptionalTest {
    public static void main(String[] args) {
        test01("small degree");
        test01(null);
    }

    public static void test01(String userName) {
        if (userName != null) {
            System.out.println("username: " + userName);
        } else {
            System.out.println("username null");
        }
    }
}

This way of writing is relatively ugly. In order to avoid the above-mentioned ugly way of writing, let the ugly design become elegant. JAVA8 provides the Optional class to optimize this writing method, which will be described in detail in the following text

2. Introduction to Optional class

Optional is a new class introduced by JDK1.8. It is a tool class without subclasses. Optional can be understood as a container, which can only store one object element or store null. Its role is mainly to solve the problem of avoiding Null checks and preventing NullPointerException.

1,Optional(T value),empty(),of(T value),ofNullable(T value)

There is a correlation between these four functions, so they are stored in a group.

Optional(T value), that is, the constructor, is private and cannot be called from the outside.

The remaining three functions are public permissions for us to call. Then, the essence of Optional is that a real value is stored inside, and when it is constructed, it is directly judged whether its value is empty. Well, it's still relatively abstract. Go directly to the source code of the Optional(T value) constructor, as shown in the figure below.

Code demo:

package com.biyu.study.optional;

import java.util.Optional;

public class OptionalTest {
    public static void main(String[] args) {
        //test01("Xiaodu");
        //test01(null);
        test02();
    }

    public static void test01(String userName) {
        if (userName != null) {
            System.out.println("username: " + userName);
        } else {
            System.out.println("username null");
        }
    }

    public static void test02() {
        Optional o1 = Optional.of("small degree");
        // Optional o2 = Optional.of(null); // If t is null, a null pointer exception will occur
        Optional o3 = Optional.empty();
        Optional o4 = Optional.ofNullable(null);
        System.out.println("o1 = " + o1);
        // System.out.println("o2 = " + o2);
        System.out.println("o3 = " + o3);
        System.out.println("o4 = " + o4);
    }
}

operation result:

o1 = Optional[small degree]
o3 = Optional.empty
o4 = Optional.empty

2. Common methods of the Optional class:

method

illustrate

isPresent()

Determine whether it contains a value, if it contains a value, it returns true, if it does not contain a value, it returns false

get()

Return the Optional if it has a value, otherwise throw NoSuchElementException

orElse(T t)

If the calling object contains a value, return the value, otherwise return the parameter t

orElseGet(Supplier s)

If the calling object contains a value, return that value, otherwise return the value retrieved by s

Code demo:

public static void test03() {
        Optional o5 = Optional.of("small degree");
        Optional o6 = Optional.empty();
        Optional o7 = Optional.ofNullable(null);

        // isPresent() : Determine whether to contain a value, return true if it contains a value, and return false if it does not contain a value.
        if (o5.isPresent()) {
            // get() : Returns the Optional if it has a value, otherwise throws NoSuchElementException.
            String userName = o5.get();
            System.out.println("username o5 for:" + userName);
        } else {
            System.out.println("username o5 for null");
        }

        if (o6.isPresent()) {
            String userName = o6.get();
            System.out.println("username o6 for:" + userName);
        } else {
            System.out.println("username o6 for null");
        }

        if (o7.isPresent()) {
            String userName = o7.get();
            System.out.println("username o7 for:" + userName);
        } else {
            System.out.println("username o7 for null");
        }
    }

operation result:

username o5 for:small degree
 username o6 for null
 username o7 for null

3. Advanced use of Optional

public static void test04() {
    Optional o8 = Optional.of("noob");
    Optional o9 = Optional.empty();

    // what does existence do
    o8.ifPresent(s -> System.out.println("username o8 for" + s));
    o9.ifPresent(s -> System.out.println("username o9 for" + s));
}

public static void test05() {
    Optional o10 = Optional.of("little black");
    Optional o11 = Optional.empty();

    // If the calling object contains a value, return that value, otherwise return the argument
    System.out.println("username o10 for: " + o10.orElse("Data does not exist 10"));
    System.out.println("username o11 for: " + o11.orElse("Data does not exist 11"));

    // If the calling object contains a value, return the value, otherwise return the value obtained by the parameter Supplier
    String s10 = o10.orElseGet(() -> {return "unknown username 10";});
    System.out.println("s10 = " + s10);

    String s11 = o11.orElseGet(() -> {return "unknown username 11";});
    System.out.println("s11 = " + s11);
}

operation result:

username o8 for Xiaobai
 username o10 for: little black
 username o11 for: Data does not exist 11
s10 = little black
s11 = unknown username

3. Summary

Optional can be understood as a container, which can only store one object element or store null. Its role is mainly to solve the problem of avoiding Null checks and preventing NullPointerException. Optional's orElse, ifPresent, orElseGet methods avoid null judgments and write more elegant and concise code.

Tags: Java jvm programming language

Posted by xmrcivicboix on Mon, 06 Mar 2023 09:37:43 +1030