When writing the processing when the value exists / does not exist in Java Optional, the following three methods can be used.
Optional.isPresent()
Optional.ifPresent()
I thought about my own guideline as to which method should be used in which case.
Optional.isPresent()
ʻOptional.isPresent ()is a method that returns
true if the value exists and
false` if it does not.
By using it in combination with the if ~ else statement, you can replace the conventional null check syntax almost as it is.
However, such usage is also said to be ** "just replacing the null check, there is no point in using Optional" **.
final Optional<String> foo = Optional.ofNullable("foo");
if (foo.isPresent()) {
System.out.println("foo=" + foo.orElse(""));
} else {
System.out.println("foo is null");
}
Optional.ifPresent() ʻOptional.ifPresent ()` is a method that executes the function (Consumer) specified by the argument if the value exists. There is a restriction that the processing when the value does not exist cannot be described and ** variables outside the block cannot be rewritten in the function **.
final Optional<String> foo = Optional.ofNullable("foo");
foo.ifPresent(f -> System.out.println("foo=" + f));
Optional.ifPresentOrElse() ʻOptional.ifPresentOrElse ()` executes the first function (Consumer) specified by the argument if the value exists, and executes the second function (Runnable) specified by the argument if it does not exist. The method. You can describe the processing when the value does not exist, but there is a restriction that ** variables outside the block cannot be rewritten in the function **.
final Optional<String> foo = Optional.ofNullable("foo");
foo.ifPresentOrElse(f -> System.out.println("foo=" + f), () -> System.out.println("foo is null"));
It is a flowchart of which method should be used in which case.
<!-TODO: Recreate the flowchart with draw.io->
Basically, it seems good to use ʻOptional.ifPresent ()` and use other methods only when you want to rewrite variables outside the block or when you want to describe the processing when the value does not exist.
Recommended Posts