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

  • A+
Category:Languages

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 [] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: