You seem to be trying to implement this mapping
Input -> Output
----- ------
true true
false false
null false
If you MUST use Optional
, the most succinct way of expressing this is
Optional.ofNullable(headers.get(BinderHeaders.NATIVE_HEADERS_PRESENT)).orElse(false);
However, you don't need Optional
at all. The following will do what you are asking for:
Boolean nhp = headers.get(BinderHeaders.NATIVE_HEADERS_PRESENT);
record.setNativeHeadersPresent((nhp == null) ? false : nhp);
If you want it in one statement (at the expense of invoking headers.get()
twice):
record.setNativeHeadersPresent(
(headers.get(BinderHeaders.NATIVE_HEADERS_PRESENT) == null)
? false
: headers.get(BinderHeaders.NATIVE_HEADERS_PRESENT));
Important Note: The use of Map#getOrDefault(...,false)
may not work. If the Map
implementation supports null
values, then getOrDefault()
can still return null
if a null
value was associated with that key. (i.e. at some point put(key,value)
with value==null
was executed). The default
value is returned only if the key was not present in the map.