CustardBun :
We are using the builder pattern to create some input for service, and it looks like something like this (simplified):
final SomeInput input = SomeInput.builder()
.withSomeId(....)
.withSomeState(....)
...
.build();
There's some attribute that we want to set in SomeInput, but only if it is present. So after creating the object, I do something like this:
Optional<String> secondaryId = infoProvider.getSecondaryId();
if (secondaryId.isPresent()) {
input.setSecondaryId(secondaryId.get());
}
I was wondering:
a) Is there a better/cleaner way to do this? b) If I do need to do it this way, can I avoid the "if" statement and utilize some functionality with Optional?
(Note: I cannot change the builder itself, and I cannot that the secondaryId is a String, but that what we retrieve from infoProvider is an optional)
Kayaman :
A little bit cleaner would be to use ifPresent
secondaryId.ifPresent(input::setSecondaryId);
but that's pretty much the best you can get with these requirements.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=465466&siteId=1