Assign value of Optional to a variable if present

前端 未结 5 2377
栀梦
栀梦 2021-02-19 02:13

Hi I am using Java Optional. I saw that the Optional has a method ifPresent.

Instead of doing something like:

Optional object = someMeth         


        
5条回答
  •  粉色の甜心
    2021-02-19 02:46

    .findFirst() returns a Optional, but if we add .orElse(null) it returns the get of the optional if isPresent(), that is (MyType), or otherwise a NULL

    MyType s = newList.stream().filter(d -> d.num == 0).findFirst().orElse(null);
    

提交回复
热议问题