Java List<T> that conditional adds Optional<T>
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.