Hi I am using Java Optional. I saw that the Optional has a method ifPresent.
Instead of doing something like:
Optional object = someMeth
Optional l = stream.filter..... // java 8 stream condition
if(l!=null) {
ObjectType loc = l.get();
Map.put(loc, null);
}
Quite late but I did following:
String myValue = object.map(x->x.getValue()).orElse("");
//or null. Whatever you want to return.
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();
.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);
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 orElseCombining these:
String myValue = object.map(MyObject::toString).orElse(null);