It is handy to declare Functions to map values and consume them if they are present.
In the situation that you have several mandatory objects, and several Optionals, I find myself wrapping the others in Optional.of(mandatoryObject) as well so I can use the same expressions on them without writing it all backwards.
Food vegetables = Food.someVegetables();
Optional<Food> condiment = Food.someCondiment();
Optional<Food> spices = Food.someSpices();
condiment.map(prepare).ifPresent(putOnPlate);
spices.map(prepare).ifPresent(putOnPlate);
But then I don't like this code:
putOnPlate.accept(prepare.apply(vegetables));
so I wrap it:
Optional.of(vegetables).map(prepare).ifPresent(putOnPlate);
But that is just wrong, because the vegetables (in this example) are not in fact optional. They are very important and I just gave everyone the impression that they are optional.
So my question is : Is there some class in java like java.util.Mandatory so I can write:
Mandatory.of(vegetables).map(prepare).definitelyPresentSo(putOnPlate);
Yes, there is such an API. You may replace
Optional.of(vegetables).map(prepare).ifPresent(putOnPlate);
with
Stream.of(vegetables).map(prepare).forEach(putOnPlate);
now having to live with the fact that the single-element Stream
is a special case of the stream of arbitrary elements (including the possible empty stream).
But you can handle all mandatory elements at once
Stream.of(mandatory1, mandatory2, mandatory3 /* etc */).map(prepare).forEach(putOnPlate);
It would be even possible to incorporate the optional elements, but it will not be as convenient as it should be, as Optional.stream()
will be introduced not until Java 9.