I am new to Java, and still learning Optionals. I understood its used to avoid Null Pointer Exception.
I have a piece of code wherein I want to use optional, which is like this:
final MetadataExtractor<FCAddress> metadataExtractor = t -> {
final Map<String, String> metadata = new HashMap<>();
metadata.put("senderCountryCode", t.getCountryCode());
metadata.put("senderState", t.getState());
metadata.put("senderPostalCode",t.getPostalCode());
return metadata;
};
Here, my use case is, if the SenderState is empty, i.e. t.getState() is empty, I want the map field to to be empty, that is not populated.
I tried something like this:
final MetadataExtractor<FCAddress> metadataExtractor = t -> {
final Map<String, String> metadata = new HashMap<>();
metadata.put("senderCountryCode", t.getCountryCode());
Optional<String> senderState = Optional.of(t.getState());
senderState.ifPresent(metadata.put("senderState", t.getState());
metadata.put("senderPostalCode",t.getPostalCode());
return metadata;
};
But this gives a compilation error, where am I going wrong in this? Error is: "ifPresent (java.util.function.Consumer) in Optional cannot be applied"