'Optional.get()' without 'isPresent()' check

JavaJava 8Java StreamOptional

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Replace get() with orElse(null).

Solution 2 - Java

...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).

Solution 3 - Java

my solution was to check it this way

if(item.isPresent()){
  item.get().setId("1q2w3e4r5t6y")
}

Solution 4 - Java

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDimsView Question on Stackoverflow
Solution 1 - JavaAndy TurnerView Answer on Stackoverflow
Solution 2 - JavaAndrew TobilkoView Answer on Stackoverflow
Solution 3 - JavaYakup AdView Answer on Stackoverflow
Solution 4 - JavaErwin SmoutView Answer on Stackoverflow