Optional

Optional.of

The method takes a non-null value as an input. If it is NULL, a NullPointerException is thrown; otherwise, a NullPointerException is returned.

Optional.ofNullable

Returns this value if it is not Null, or an option.empty () if it is Null.

Optional.empty()

Returns an empty Optional instance through the constructor.

Optional<User> user = Optional.ofNullable(getUserById(id));
if (user.isPresent()) {
    String username = user.get().getUsername();
    System.out.println("Username is: " + username); / / use the username
}
Copy the code

The code is nice — but it’s actually not that different from the code that used to check for null values. Instead, it wraps the value with Optional, increasing the amount of code.

Optional.ifPresent

Better use Optional:

User user = userService.getUser(userId);
Optional<User> optionalUser = Optional.ofNullable(user);
// Call the contents of ifPresent if there is a value
optionalUser.ifPresent(value -> log.debug(value.getUsername()));
Copy the code

Consumer, the functional interface for JDK8, wraps arguments for consumption as inputs to lambda expressions

If Optional has a value, it calls consumer.accept (value).

orElse

User unknown = Optional.ofNullable(user).orElse(new User(0."Unknown"));
Copy the code

orElseGet

User unknownGet = Optional.ofNullable(userService.getUser(userId)).orElseGet(() -> new User(0."UnknownGet"));
Copy the code

Both are used to match custom defaults when the input parameter is null

public static void main(String[] args) {
    String name = Optional.of("baeldung").orElse(getRandomName());
    log.info(name);
}

private static String getRandomName(a) {
    List<String> names = new ArrayList<>();
    names.add("zhangsan");
    names.add("Bill");
    names.add("wangwu");

    log.info("getRandomName() method - start");

    Random random = new Random();
    int index = random.nextInt(3);
    log.debug("getRandomName() method - end");
    return names.get(index);
}
Copy the code

Remember (from the Javadoc) that the Supplier method passed as an argument is only executed when *an Optional* value is not present.

The difference between:
  1. OrElse differs from orElseGet in that its input parameter is a generic T, while orElse is the result of a functional method.
  2. The code in orElse executes even if the value of ofNullable is null

orElseThrow

Raises an exception when null in Optional

User user = Optional
        .ofNullable(getUserById(id))
        .orElseThrow(() -> new EntityNotFoundException("Id" + id + "User not found"));
Copy the code

map

String password = " password ";
Optional<String> passOpt = Optional.of(password);
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();//false
boolean password1 = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent();//true
Copy the code

filter

Person person = new Person("NICK",22); Optional<Person> personOptional = Optional.ofNullable(person); Optional<String> optionalName = personOptional .map(Person::getName) .orElseThrow(() -> new RuntimeException(" Your nameOptionalWrapper girlfriend has no name!" ));Copy the code