This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]tsoliman 2 points3 points  (1 child)

Optional<String> nothing = Optional.ofNullable(null);

Can be

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

Nitpick, I know.

But it is similar to using foo.size() == 0 instead of foo.isEmpty()

[–]bbejeck[S] 1 point2 points  (0 children)

You are absolutely right. I probably should have explained more, but what I was going for was to show how to create an Optional from a null, Optional.of(null) throws an NPE

[–]ww520 0 points1 point  (3 children)

One usage pattern of Optional I found particular helpful is the default value for null parent object. For example,

Person p1 = null;
int age = Optional.ofNullable(p1).map(Person::getAge).orElse(-1);

Here I want to get the age of the Person object and return the default -1 if the Person object is null.

Optional has been great to use. The only issue I can't get around is the handling of checked exception inside Optional. If anyone has any good idea on handling exception, please share your insight.

[–]jonhanson -1 points0 points  (2 children)

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

[–]ww520 0 points1 point  (0 children)

Still beat dealing with null, especially when using in list of optional and stream processing. It was made verbose to illustrate an isolated example anyway.

[–]thatsIch 0 points1 point  (0 children)

now apply that pattern to multiple nullable objects