Basic use of Optional class in Java8

1. Introduction

  • Optional is a container object that may or may not contain a certain value.
  • It is designed to solve the null pointer exception problem.
  • Using Optional avoids explicitly checking for null values ​​in your code, making your code more concise and readable.

2. Common usage of Optional:

1. Create an Optional object:

1.1 Use of() method:

Creates an Optional object containing the specified non-null value.

Here is an example of using the of() method to create an Optional object:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        String value = "Hello World!";
        Optional<String> optional = Optional.of(value);

        // 检查Optional是否包含值
        if (optional.isPresent()) {
    
    
            System.out.println("Optional包含值: " + optional.get());
        } else {
    
    
            System.out.println("Optional为空");
        }
    }
}

In this example, we use the of() method to create an Optional object containing a non-null value. We then check if the Optional contains a value by calling the isPresent() method. If Optional contains a value, call the get() method to obtain the value and print the output; otherwise, the printed output Optional is empty.

The output is:

Optional包含值: Hello World!

Note: When using the of() method, if the value passed in is null, a NullPointerException will be thrown immediately. Therefore, when using the of() method to create an Optional object, you need to ensure that the value passed in is not empty. If the value may be null, you can create an Optional object using the ofNullable() method, which can accept null values.

1.2 Use ofNullable() method:

Creates an Optional object containing the specified value, or an empty Optional object if the value is null.

Here is an example of using the ofNullable() method to create an Optional object:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        String value = null;
        Optional<String> optional = Optional.ofNullable(value);

        // 检查Optional是否包含值
        if (optional.isPresent()) {
    
    
            System.out.println("Optional包含值: " + optional.get());
        } else {
    
    
            System.out.println("Optional为空");
        }
    }
}

In this example, we use ofNullable() method to create an Optional object containing the specified value. If the value is null, an empty Optional object is created. We then check if the Optional contains a value by calling the isPresent() method. If Optional contains a value, call the get() method to obtain the value and print the output; otherwise, the printed output Optional is empty.

The output is:

Optional为空

Note: Optional objects created using ofNullable() method can accept null values ​​and will not throw NullPointerException immediately. This allows for more flexibility in handling potentially null values.

1.3 Use empty() method:

Create an empty Optional object.

Here is an example of using the empty() method to create an empty Optional object:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Optional<String> optional = Optional.empty();

        // 检查Optional是否包含值
        if (optional.isPresent()) {
    
    
            System.out.println("Optional包含值: " + optional.get());
        } else {
    
    
            System.out.println("Optional为空");
        }
    }
}

In this example, we create an empty Optional object using the empty() method. We then check if the Optional contains a value by calling the isPresent() method. Since the Optional object we created using the empty() method is empty, the return value of isPresent() is false, and the program will print out that the Optional is empty.

The output is:

Optional为空

Optional objects created using the empty() method are always empty and do not contain any value. This can be used to represent missing values ​​in some cases.

2. Determine whether Optional contains a value:

2.1 Use isPresent() method:

Returns true if the Optional object contains a value, false otherwise.

3. Get the value in Optional:

3.1 Use the get() method:

If the Optional object contains a value, the value is returned, otherwise a NoSuchElementException is thrown.

Here is a sample code:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Optional<String> optional = Optional.of("Hello World");

        try {
    
    
            String value = optional.get();
            System.out.println("Optional的值: " + value);
        } catch (NoSuchElementException e) {
    
    
            System.out.println("Optional为空");
        }
    }
}

In this example, we use the of() method to create a non-null Optional object and pass the string "Hello World" as the value. Then, we use the get() method to obtain the value of the Optional object and perform corresponding operations.

The output is:

Optional的值: Hello World

If we set the Optional object to empty:

Optional<String> optional = Optional.empty();

Then optional.get() will throw NoSuchElementException because the Optional object is empty.

Please note that when using the get() method, you must first use the isPresent() method to check whether the Optional object contains a value to avoid throwing an exception.

3.2 Use the orElse() method:

If the Optional object contains a value, then that value is returned, otherwise the specified default value is returned.

Here is a sample code:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Optional<String> optional = Optional.of("Hello World");
        
        String value = optional.orElse("Default Value");

        System.out.println("Optional的值: " + value);
    }
}

In this example, we use the of() method to create a non-null Optional object and pass the string "Hello World" as the value. Then, we use the orElse() method to get the value of the Optional object. If the Optional object is empty, the specified default value "Default Value" is returned.

The output is:

Optional的值: Hello World

If we set the Optional object to empty:

Optional<String> optional = Optional.empty();

Then optional.orElse("Default Value") will return the specified default value "Default Value" because the Optional object is empty.

When using the orElse() method, you can avoid throwing exceptions and provide a default value to handle the case where the Optional object is empty.

3.3 Use orElseGet() method:

If the Optional object contains a value, the value is returned, otherwise a default value is generated by calling the method provided by the Supplier interface.

Here is a sample code:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Optional<String> optional = Optional.empty();
        
        String value = optional.orElseGet(() -> generateDefaultValue());

        System.out.println("Optional的值: " + value);
    }
    
    public static String generateDefaultValue() {
    
    
        System.out.println("生成默认值");
        return "Default Value";
    }
}

In this example, we create an empty Optional object using the empty() method. Then, we use the orElseGet() method to get the value of the Optional object. If the Optional object is empty, a default value is generated by calling the generateDefaultValue() method.

The generateDefaultValue() method is a custom method used to generate default values. In this example, we simply print a message "Generate Default Value" and then return the default value "Default Value".

The output is:

生成默认值
Optional的值: Default Value

Since the Optional object is empty, the generateDefaultValue() method is called to generate a default value.

When using the orElseGet() method, the Supplier interface provides a more flexible way to generate default values, such as using lambda expressions or method references. This allows us to dynamically generate default values ​​as needed.

3.4 Use orElseThrow() method:

If the Optional object contains a value, the value is returned, otherwise the specified exception is thrown by calling the method provided by the Supplier interface.

Here is a sample code:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Optional<String> optional = Optional.empty();
        
        try {
    
    
            String value = optional.orElseThrow(() -> new IllegalArgumentException("值为空"));
            System.out.println("Optional的值: " + value);
        } catch (IllegalArgumentException e) {
    
    
            System.out.println("捕获到异常: " + e.getMessage());
        }
    }
}

In this example, we create an empty Optional object using the empty() method. Then, we use the orElseThrow() method to get the value of the Optional object. If the Optional object is empty, the specified exception is thrown by calling the method provided by the Supplier interface.

In this example, we use lambda expression () -> new IllegalArgumentException ("value is empty") as the implementation of the Supplier interface. When the Optional object is empty, an IllegalArgumentException exception will be thrown, and the exception message is specified as "value" Is empty".

The output is:

捕获到异常: 值为空

Since the Optional object is empty, an IllegalArgumentException exception is thrown and the exception message is printed.

When using the orElseThrow() method, the Supplier interface can provide a more flexible way to throw exceptions, such as using lambda expressions or method references. This allows us to dynamically throw different exceptions as needed.

4. Convert the value in Optional:

4.1 Use map() method:

Convert the value in Optional and return a new Optional object.

Here is a sample code:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Optional<String> optional = Optional.of("Hello");
        
        Optional<String> result = optional.map(value -> value + " World");
        System.out.println("转换后的Optional的值: " + result.orElse(""));
    }
}

In this example, we use the of() method to create an Optional object containing the value "Hello". We then use the map() method to transform the value and concatenate it with "World". Finally, we use the orElse() method to get the converted value, and if the converted Optional object is empty, an empty string is returned.

The output is:

转换后的Optional的值: Hello World

Since Optional objects contain values, the map() method concatenates the value with "World" and returns a new Optional object. Finally, we get the converted value through the orElse() method and print it to the console.

Using the map() method can easily convert the value of the Optional object without the need for additional null value checking. This makes the code more concise and readable.

4.2 Use flatMap() method:

Convert the value in Optional and return a new Optional object.

Here is a sample code:

import java.util.Optional;

public class OptionalDemo {
    
    
    public static void main(String[] args) {
    
    
        Optional<String> optional = Optional.of("Hello");
        
        Optional<String> result = optional.flatMap(value -> Optional.of(value + " World"));
        System.out.println("转换后的Optional的值: " + result.orElse(""));
    }
}

In this example, we use the of() method to create an Optional object containing the value "Hello". We then use the flatMap() method to convert the value, concatenate it with "World", and use the of() method to wrap the result into a new Optional object. Finally, we use the orElse() method to get the converted value, and if the converted Optional object is empty, an empty string is returned.

The output is:

转换后的Optional的值: Hello World

Since Optional objects contain values, the flatMap() method concatenates the value with "World" and returns a new Optional object. Finally, we get the converted value through the orElse() method and print it to the console.

The value of the Optional object can be easily converted using the flatMap() method, and multiple conversion operations can be called in a chain. This makes the code more flexible and readable.

Guess you like

Origin blog.csdn.net/qq_39939541/article/details/132308574