Treat Optional Null or Empty using lambda functions

Asked

Viewed 19 times

0

Let’s say I have the following methods:

public Optional<List<String>> doSomething1() {
     // do something
     return null;
}

public Optional<List<String>> doSomething2() {
     // do something
     return Optional.empty();
}

NOTE: This method is an outsider, so I can’t tell him not to send null.

That way, when I get on my application, I’m not getting to treat right:

 List<String> list = doSomething1().orElseGet(Collections::emptyList);

When I implement the above code, a nullPointerException is returned

 List<String> list = Optional.ofNullable(doSomething1()).map(Optional::get).orElseGet(Collections::emptyList);

When I implement the above code, it is successful for the doSomething1 method. However for the doSomething2 method a Nosuchelementexception is returned

There is a way to treat for both scenarios ?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.