Sergii Sergii - 1 year ago 108
Java Question

Java8 simplify expression using Optional

I have an code block:

public Builder withMultiValueMap(MultiValueMap<String, String> multiValueMap) {
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 Source

The syntax that has the same result as this expression:

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



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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download