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

后端 未结 4 2288
无人共我
无人共我 2020-12-05 04:03

I have the following search code in Java:

return getTableViewController().getMe().getColumns().stream().filter($->Database.equalsColumnName($.getId(), col         


        
相关标签:
4条回答
  • 2020-12-05 04:06

    my solution was to check it this way

    if(item.isPresent()){
      item.get().setId("1q2w3e4r5t6y")
    }
    
    0 讨论(0)
  • 2020-12-05 04:08

    Replace get() with orElse(null).

    0 讨论(0)
  • 2020-12-05 04:23
    ...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).

    0 讨论(0)
  • 2020-12-05 04:26

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

    0 讨论(0)
提交回复
热议问题