0

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?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Sergii
  • 7,044
  • 14
  • 58
  • 116
  • 3
    I don't know about better... `Optional.ofNullable(respondentId).map(Long::valueOf).orElse(null))` – Marko Topolnik Sep 28 '16 at 15:09
  • Super. This is exactly i need! Thank you. please add an answer to mark it solved. – Sergii Sep 28 '16 at 15:11
  • 1
    The code will be cleaner refactor such that the `withRespondentId` method doesn't require a `null` (maybe initialize with the `null` scenario set). You could then write `Optional.ofNullable(respondentId).map(Long::valueOf).ifPresent(this::withRespondentId);` – flakes Sep 28 '16 at 15:20

2 Answers2

1

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

If MultiValueMap is your own class, you can migrate getFirst to

Optional<V> getFirst(K key);

multiValueMap.getFirst(key).map(Long::valueOf).getOrElse(null);
Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27