What is Optional? It is a memorandum article for myself at that time. As a rough idea, the optional type is a type that you can see at a glance that "null may be included". First, a simple null check example
if (name != null) {
System.out.println(name);
} else {
System.out.println("I don't have a name");
}
Of course the result
//to name"I have a name"When assigned to
I have a name
//If name is null
I don't have a name
If you do this with Optional, it looks like this
Optional.ofNullable(name).ifPresentOrElse(result -> System.out.println(result),
() -> System.out.println("I don't have a name"));
In this case as well, the result is as follows
//to name"I have a name"When assigned to
I have a name
//If name is null
I don't have a name
In the first place, there are more ways to write a normal if statement ... Or something like that, if you put it aside and explain what you are doing above Optional.ofNullable(name) If the value of the argument is not null in the part of, the Optinal that stores the value is returned. As the name suggests, it is a method that allows null, and if it is null, it returns an empty Optional generated by the optional empty method. Compare this empty Optional, == new with the empty Optional ... I don't do anything like that.
That's where ifPresent, a method of the Optional class, comes up. So, I thought about using ifPresent this time, but I saw many articles saying that ifPresent should not be used in various places. Apparently, if the Optional that I got first was empty, the main reason was that the else processing was troublesome. So this time, I used *** ifPresentOrElse *** newly added from java9. *** ifPresentOrElse (result-> System.out.println (result), ()-> System.out.println ("no name")) *** It is a method that is easy to understand at a glance and can sort the processing depending on whether the Optional obtained first is empty.
With this kind of feeling, process the value that may be null without approaching it with if null etc. I think it has the advantage of not only being able to write neatly, but also preventing forgetting to check for nulls.
So far this time, what is Optional?
Recommended Posts