Is there a library (e.g. Apache, Guava) that provides a List<T>
with a method
void add(Optional<T> element)
that adds the element if it is present, (and is a no-op if !element.isPresent()
)? Obviously easy to implement, but it seems like such an obvious thing it seems someone might have done it already.
Instead of list.add(optio)
you just need :
optio.ifPresent(list::add);
Example :
Optional<Integer> optio = Optional.ofNullable(Math.random() > 0.5 ? 52 : null);
List<Integer> list = new ArrayList<>();
optio.ifPresent(list::add);
System.out.println(list); //50% of [52], 50% of []
Obviously easy to implement, but it seems like such an obvious thing it seems someone might have done it already.
Well, sometimes the obvious things are the things that are left out as they're simple. Nevertheless, this is not something that's available in the Java standard library and don't see it anytime soon either due to the fact that Optionals were intended to be used as method return types instead of method parameters.
Also, "if this method were to be available" then it would require yet another add
method overload polluting the API when it would be simple to do as @azro suggests for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With