Java8 Optional wrapper class

Posted by ShopMAster on Tue, 04 Jan 2022 14:18:18 +0100

Basic understanding

Java 8 adds an Optional wrapper class to avoid NPE problems as much as possible.

First, Optional is a container for possible null values, which can handle null reasonably and gracefully.

Optional indicates that the static method of null is optional Empty() actually makes a layer of wrapper outside null. At the same time, the wrapper class provides many methods.

Based on Java 8, both functional style and lambda expression are added. The methods provided by the Optional class are also based on this. The Optional class hopes to calculate or extract functions in the Optional wrapper class for possible null values. Many methods of the Optional class will perform null verification on the data before execution, so as to avoid NPE as much as possible.

Built in function interface

Optianol method

1. Optional.of()/Optional.ofNullable(): create an optional object
. of() creates an Optional object, and throws NPE if value is null. ofNullable(), there is no such restriction.

    String empty = null;
    Optional<String> emptyOpt = Optional.ofNullable(empty);
	// Throwing anomaly
	Optional<String> empty2Opt = Optional.of(empty);

Not recommended of()

2. isPresent(): judge whether the value exists and return the boolean value

	Optional<String> testOpt = Optional.ofNullable("test");
	System.out.println(testOpt.isPresent() == true);

Judge whether there is a value in Optional and return boolean. It is useful in some cases, but try not to use it in the if judgment body?

3. Ifpresent (consumer <? Super T > consumer): if the value saved by the option object is not null, the consumer object will be called, otherwise it will not be called

	Optional<String> testOpt = Optional.ofNullable("test");
	testOpt.ifPresent(s -> System.out.println(s));

Recommended. It has no performance advantage, but it can make the code more concise. It is also the style that Java 8 wants to use.

4. get()/orElse(value)/orElseGet(Supplier<? extends T> other)
get() returns the value wrapped in Optional. Do not use it directly before blank judgment.
orElse(value): if the value saved by the optional object is not null, the original value is returned; otherwise, value is returned
orElseGet(Supplier supplier): the function is the same as orElse, except that the orElseGet parameter is an object

    Optional<String> testOpt = Optional.ofNullable(null);
    testOpt.orElseGet(() -> {

orElseGet() is recommended

5. orElseThrow(): throw an exception if the value does not exist, and do nothing if the value exists, which is somewhat similar to Guava's precodings

6. Filter (predicate <? Super T > predicate): if there is a value and the assertion conditions are met, the Optional containing the value is returned; otherwise, the null option is returned.

    Optional<String> filterOpt = Optional.ofNullable("test");
    Optional<String> middleOpt = filterOpt.filter(s -> {
        System.out.println("get into Filter Assert");
        return "1".equalsIgnoreCase(s);
    // When the value value of filter2Opt is null, the assertion is not executed
	Optional<String> filter2Opt = Optional.ofNullable(null");
    Optional<String> middle2Opt = filterOpt.filter(s -> {
        System.out.println("No entry Filter Assert");
        return "1".equalsIgnoreCase(s);

When the value value of filter2Opt is null, the assertion is not executed to avoid NPE.

7. < U > Optional < U > map (Function <? Super T,? Extends U > mapper): if the parameter mapper has a value, call the map method to execute the Function method of the mapper parameter to get the return value. If the return value of the mapper is not null, an option containing the mapping return value is created as the return value of the map method; otherwise, an empty option is returned. If the mapper parameter passed in is null, an NPE is thrown

	// When the value value of mapOpt is null, the method body is not executed
	Optional<String> mapOpt = Optional.empty();
    Optional<String> middleOpt = -> {
    	System.out.println("No entry Func");
        return s + "1";

	Optional<String> map2Opt = Optional.ofNullable("test");
    Optional<String> middle2Opt = -> {
        System.out.println("get into Func");
        return s + "new";

The map method is mostly used for a series of calling methods to find the last object that really needs to be processed, using the streaming call style. The code is cleaner.

Topics: Java