7

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.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
gerardw
  • 5,822
  • 46
  • 39
  • 6
    `Optional` as a method parameter seems to be discouraged, so chances are it is not implemented in popular libraries. Beside that, it's probably easier to just do `element.ifPresent(list::add)` – ernest_k Dec 02 '18 at 19:22
  • 9
    `list.add(optio)` ==> `optio.ifPresent(list::add)` – azro Dec 02 '18 at 19:26
  • Would you mind thinking about accepting an answer if it satisfies you ? ;) – azro Feb 13 '19 at 09:59

2 Answers2

14

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 []
azro
  • 53,056
  • 7
  • 34
  • 70
2

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126