With java 8 Optional, Is there a way to write this line of code:
Bar bar = fooOpt.isPresent() ? new Bar(fooOpt.get().getX()) : null;
something like:
Bar bar = fooOpt.ifPresent(f -> new Bar(f.getX()), null)
Perhaps you are looking for:
Optional<Foo> fooOpt = ...
Bar bar = fooOpt.map(foo -> new Bar(foo.getX()))
.orElse(null);
Given:
public class Foo {
Object getX() {
...
}
}
public class Bar {
public Bar(Object x) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With