How can I convert the below legacy java code to use Optional:
if (outer != null
&& outer.getInnerMethod() != null
&& outer.getInnerMethod().isAllowed()) {
Obj value = outer.getInnerMethod().getSomethingElse();
}
Using something like Optional.ofNullable took me till here -
Optional.ofNullable(Outer.getOuter)
.map(Outer::getInnerMethod)
.map(SomethingElse::isAllowed)
.ifPresent(.. );
But ifPresent will not have access to the outer object. What would be the cleanest way to transform something like this?
Do this
Optional.ofNullable(Outer.getOuter)
.filter(outer -> ::Objects.nonNull(outer.getInnerMethod()))
.filter(SomethingElse::isAllowed)
.map (.. ); //or whatever operation you want to do here
Use filter
instead of map
. From the java doc
If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
Optional<Obj> optional = Optional.ofNullable(Outer.getOuter)
.map(Outer::getInnerMethod)
.filter(SomethingElse::isAllowed)
.map(SomethingElse::getSomethingElse);
Instead of using map to chech if it's allowed use filter(e -> e.isAllowed())
this will filter out anything that isn't allowed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.