0

I have this statement in java

if (payload.get("mimeType") != null) {
    lettersPayload.put("mimeType", payload.get("mimeType"));

    if (!StringUtils.isEmpty(heytype) && !"all".equals(type)) {
        lettersPayload.put("heytype", heytype);
    }
}

I have a requirment to do this code snippet with Optional.ofNullable().ifPresent() I wrote these:

Optional.of(payload.get("mimeType")).ifPresent(name -> lettersPayload.put("heytype", heytype));

The second statement is crushing

Any ideas? Thanks!

deHaar
  • 17,687
  • 10
  • 38
  • 51
RamAlx
  • 6,976
  • 23
  • 58
  • 106
  • "is crushing" ... isPresent doesn't take parameters afaik. – Stultuske Dec 12 '19 at 12:13
  • 2
    If `requestPayload.get(MIME_TYPE)` may be null, you should use `Optional.ofNullable`. – Eran Dec 12 '19 at 12:14
  • 1
    are you trying to solve nested `if`s using `Optional`? rather than using `ifPresent` to perform an operation, make use if `isPresent` to check and perrforrm both the operation, even if that is so.. Something like `Optional opt = Optional.ofNullable(payload.get("mimeType")); opt.ifPresent(p -> lettersPayload.put("mimeType", p)); if(opt.isPresent() && !StringUtils.isEmpty(heytype) && !"all".equals(type)) { lettersPayload.put("heytype", heytype); }` which reads worse than your current code. – Naman Dec 12 '19 at 12:17

1 Answers1

3

You need to use ofNullable if you are not sure whether the value you want to wrap as Optional is null or not.

Your code can then be rewritten:

Optional.ofNullable(payload.get("mimeType")).ifPresent(mimeType -> {...})
fbiville
  • 8,407
  • 7
  • 51
  • 79