Skip to main content
 

Protip: Use Optional#asSet() to populate collections from optional values.

Was annoyed with lots and lots of code that looks like this:
   Optional<Foo> foo = getFoo();
   if (foo.isPresent()) {
     collection.add(foo.get());
   }

Turns out there's asSet which lets you write code like this:

  collection.addAll(getFoo().asSet());