Sergii Sergii - 2 months ago 13
Java Question

Java8 simplify expression using Optional

I have an code block:

public Builder withMultiValueMap(MultiValueMap<String, String> multiValueMap) {
...
withRespondentId(Long.valueOf(multiValueMap.getFirst("respondentId")));
...
return this;
}


Sometimes map can return null if no value for respondentId key.
I can process it in old way using something like

String respondentId = multiValueMap.getFirst("respondentId");
withRespondentId(respondentId == null? null: Long.valueOf(respondentId));


...but I want do it better!

Is it possible simplify using java8 Optional or other stuff?

Answer

The syntax that has the same result as this expression:

respondentId == null? null: Long.valueOf(respondentId)

is

Optional.ofNullable(respondentId).map(Long::valueOf).orElse(‌​null)

Since it's actually longer, it's not a complete win, although it might pass as more readable.

Comments