Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short version of check if the result of an object in not null then cast to boolean and set in Java

I have been looking for a short version of the following statement in Java:

if(headers.get(BinderHeaders.NATIVE_HEADERS_PRESENT) !=null ) {
      record
          .setNativeHeadersPresent((boolean) headers.get(BinderHeaders.NATIVE_HEADERS_PRESENT));
    }

If I would like to use Optional.ofNullable it doesn't work as I need to cast the object to boolean as well.

P.S: I am using Java8.

like image 955
Ali Avatar asked Jan 01 '26 03:01

Ali


1 Answers

It's not what Optional.ofNullable for, but I will share how it can be done because I love method references.

Optional.ofNullable(headers.get(BinderHeaders.NATIVE_HEADERS_PRESENT))
        .map(boolean.class::cast)
        .ifPresent(record::setNativeHeadersPresent);

Since you've got a Map<String, String>, Map#getOrDefault could be an option.

record.setNativeHeadersPresent(
    Boolean.parseBoolean(
        headers.getOrDefault(BinderHeaders.NATIVE_HEADERS_PRESENT, "false")
    )
);
like image 117
Andrew Tobilko Avatar answered Jan 04 '26 17:01

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!