Return null or new object using Optional object fields

Multi tool use


Return null or new object using Optional object fields
We have a method, wherein we receive an Optional<SomeType>
object. If the contained SomeType
object is not null then we have to initialize a SomeOtherType
object using the fields of the SomeType
object and return that new object; otherwise we have to return null
Optional<SomeType>
SomeType
SomeOtherType
SomeType
We found multiple different solutions where we perform this task with two statements, first retrieving the optional object and then second creating the other type object e.g.
private SomeOtherType ourMethod() {
SomeType someObject = getOptionalSomeTypeFromSomeWhere().orElse(null);
return someObject != null ? new SomeOtherType(someObject.getField1(), someObject.getField2(), ...) : null;
}
Is it possible to cover this with one statement? So far we could not figure to do the null checks, accessing the fields, new object creation etc. all in one
Basically a more complex case of this question: Get field of optional object or return null
Optional
null
@davidxxx: Thanks for pointing this out. The concept was clear, but you are right that the phrasing was not good; changed it now
– hammerfest
27 mins ago
@davidxxx: Your comment was actually also useful to notice that I failed to escape the angle brackets, so only
Optional
was visible instead of Optional<SomeType>
– hammerfest
21 mins ago
Optional
Optional<SomeType>
1 Answer
1
Use Optional.map
:
Optional.map
return getOptionalSomeTypeFromSomeWhere()
.map(someObject -> new SomeOtherType(someObject.getField1(), someObject.getField2(), ...)
.orElse(null);
Thank you. We tried map() too, but could not nail the syntax.
– hammerfest
40 mins ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
"We have a method, wherein we receive an Optional object, which might be null." Note that the
Optional
should never refer to a null reference : it defeats its purpose. Only the contained object could refer tonull
.– davidxxx
32 mins ago