Assign value of Optional to a variable if present

前端 未结 5 2421
栀梦
栀梦 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:50

    You need to do two things:

    1. Turn your Optional into an Optional, which has a value iff the original Optional had a value. You can do this using map: object.map(MyObject::toString) (or whatever other method/function you want to use).
    2. Get the String value of of your Optional, or else return a default if the Optional doesn't have a value. For that, you can use orElse

    Combining these:

    String myValue = object.map(MyObject::toString).orElse(null);
    

提交回复
热议问题