Assign value of Optional to a variable if present

不羁的心 提交于 2019-12-22 03:51:31

问题


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

Instead of doing something like:

Optional<MyObject> object = someMethod();
if(object.isPresent()) {
    String myObjectValue = object.get().getValue();
}

I wanted to know how I can use the Optional.ifPresent() to assign the value to a variable.

I was trying something like:

String myValue = object.ifPresent(getValue());

What do I need the lambda function to be to get the value assigned to that variable?


回答1:


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

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

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



回答2:


Quite late but I did following:

String myValue = object.map(x->x.getValue()).orElse("");
                           //or null. Whatever you want to return.



回答3:


You need to do two things:

  1. Turn your Optional<MyObject> into an Optional<String>, 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<String>, 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);



回答4:


Optional l = stream.filter..... // java 8 stream condition

        if(l!=null) {
            ObjectType loc = l.get();
            Map.put(loc, null);
        }



回答5:


.findFirst() returns a Optional<MyType>, 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);


来源:https://stackoverflow.com/questions/39713058/assign-value-of-optional-to-a-variable-if-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!