Reputation: 4177
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?
Upvotes: 21
Views: 98484
Reputation: 591
.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);
Upvotes: 2
Reputation: 7
Optional l = stream.filter..... // java 8 stream condition
if(l!=null) {
ObjectType loc = l.get();
Map.put(loc, null);
}
Upvotes: -1
Reputation: 4507
Quite late but I did following:
String myValue = object.map(x->x.getValue()).orElse("");
//or null. Whatever you want to return.
Upvotes: 21
Reputation: 43391
You need to do two things:
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).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);
Upvotes: 12
Reputation: 399
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();
Upvotes: 22