optional description

1. Description

public final class Optional<T>
extends Object

A container object that may or may not contain non-null values. If a value exists, isPresent()will return trueand get()will return the value.

Provides additional methods that depend on the presence or absence of the containing value, such as orElse()(return default if value not present) and ( execute code block ififPresent() value present ).

Optional is a container: it can hold a value of type T, or just null. Optional provides many useful methods so that we don't need to explicitly check for null values.

The introduction of the Optional class is a good solution to the null pointer exception.

2.API

3. Common methods and examples

Common methods of the Optional container class:

Optional.of(T t) : Creates 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() : Determine whether a value is contained.

orElse(T t) : If the calling object contains a value, return that value, otherwise return t.

orElseGet(Supplier s) : If the calling object contains a value, return that 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().

fiatMap(Function mapper); Similar to map, the return value must be Optional.

Example:

package com.example.demo.optional;

import com.example.demo.domain.Student;

import java.util.Optional;

/**
 * @Author linaibo
 * @Date 2023/2/26 14:22
 * @PackageName:com.example.demo.optional
 * @ClassName: OptionalDemo1
 * @Version 1.0
 */
public class OptionalDemo1 {
    public static void main(String[] args) {

        // of方法: 创建一个 Optional 实例。
        Optional<Student> student = Optional.of(new Student());
        if (student.isPresent()) {
            // 执行结果
            System.out.println(student.get());
        } else {
            System.out.println("不存在");
        }

        // empty方法:创建一个空的 Optional 实例。结果为不存在
        Optional<Object> empty = Optional.empty();
        if (empty.isPresent()) {
            empty.get();
        } else {
            // 执行结果
            System.out.println("不存在");
        }

        // ofNullable:若 t 不为 null,创建 Optional 实例,否则创建空实例。
        Optional<Student> student1 = Optional.ofNullable(new Student());
        if (student1.isPresent()) {
            // 执行结果
            System.out.println(student1.get());
        } else {
            System.out.println("不存在");
        }

        // orElse(T t) : 如果调用对象包含值,返回该值,否则返回t。
        // 有值的场合
        Optional<Student> empty1 = Optional.of(new Student());
        Student student2 = new Student();
        student2.setStudentId(1);
        student2.setStudentNo("123");
        student2.setStudentName("张三");
        Student student3 = empty1.orElse(student2);
        System.out.println(student3);
        // 无值的场合
        Optional<Student> empty12 = Optional.empty();
        Student student22 = new Student();
        student22.setStudentId(1);
        student22.setStudentNo("123");
        student22.setStudentName("张三");
        Student student33 = empty12.orElse(student22);
        System.out.println(student33);

        // orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值。
        Optional<Student> empty2 = Optional.empty();
        Student studen5 = empty2.orElseGet(() -> {
            Student student4 = new Student();
            student4.setStudentId(1);
            student4.setStudentNo("123");
            student4.setStudentName("张三");
            return student4;
        });
        System.out.println(studen5);
    }
}

error example:

        // empty方法:创建一个空的 Optional 实例。结果为不存在
        Optional<Object> empty = Optional.empty();
            empty.get();

执行结果:
Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.util.Optional.get(Optional.java:135)
	at com.example.demo.optional.OptionalDemo1.main(OptionalDemo1.java:29)

表示被请求的元素不存在。
        Optional<Object> empty = Optional.of(null);
        if (empty.isPresent()) {
            empty.get();
        } else {
            // 执行结果
            System.out.println("不存在");
        }

执行结果:
Exception in thread "main" java.lang.NullPointerException
	at java.util.Objects.requireNonNull(Objects.java:203)
	at java.util.Optional.<init>(Optional.java:96)
	at java.util.Optional.of(Optional.java:108)
	at com.example.demo.optional.OptionalDemo1.main(OptionalDemo1.java:27)

在of方法中直接传递一个null,则会出现空指针异常。

4. Summary

The return value of the method can be wrapped with optional to avoid null pointers.

Generally, the ofNullable() method is called, and then the isPresent() method is used to determine whether there is a value. If there is no value, an exception is thrown directly; if there is value, continue to follow-up processing. Of course, sometimes the object passed in may be an empty object. When using a specific item of an object, a judgment is made to see if it has a value.

Guess you like

Origin blog.csdn.net/m0_72167535/article/details/129226411