Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List<T> that conditional adds Optional<T>

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.

like image 630
gerardw Avatar asked Dec 02 '18 19:12

gerardw


2 Answers

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 []
like image 194
azro Avatar answered Nov 18 '22 13:11

azro


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.

like image 29
Ousmane D. Avatar answered Nov 18 '22 12:11

Ousmane D.