'Optional.get()' without 'isPresent()' check
I have the following search code in Java:
return getTableViewController().getMe().getColumns().stream()
.filter($ -> Database.equalsColumnName($.getId(), columnId))
.findFirst()
.get();
I was wishing to find column by name and return first one found.
I understand there is a case when nothing found and it should be processed, but how?
Is this what it wants by this swearing:
'Optional.get()' without 'isPresent()' check
?
How to fix? I wish to return null
if nothing found.
UPDATE
Okay, okay, I just didn't realize, that findFirst()
returns Optional
.
Replace get()
with orElse(null)
.
...findFirst().orElse(null);
Returns the value if present, otherwise returns null
. The documentation says that the passed parameter may be null
(what is forbidden for orElseGet
and orElseThrow
).
my solution was to check it this way
if(item.isPresent()){
item.get().setId("1q2w3e4r5t6y")
}
Optional was created so code could after all these decades, finally start avoiding null.
Remove the .get(), return the Optional itself and make the calling code deal with it appropriately (just as it would have to do in the case you'd be returning null).