问题
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:
- Turn your
Optional<MyObject>into anOptional<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). - 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