Assign value of Optional to a variable if present

前端 未结 5 2373
栀梦
栀梦 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

    You could use #orElse or orElseThrow to improve the readbility of your code.

    Optional object = someMethod();
    String myValue = object.orElse(new MyObject()).getValue();
    

    Optional object = someMethod();
    String myValue = object.orElseThrow(RuntimeException::new).getValue();
    

提交回复
热议问题