Uses for Optional

Having been using Java 8 now for 6+ months or so, I’m pretty happy with the new API changes. One area I’m still not confident in is when to use Optional. I seem to swing between wanting to use it everywhere something may be null, and nowhere at all.

There seem to be a lot of situations when I could use it, and I’m never sure if it adds benefits (readability / null safety) or just causes additional overhead.

So, I have a few examples, and I’d be interested in the community’s thoughts on whether Optional is beneficial.

1 – As a public method return type when the method could return null:

public Optional<Foo> findFoo(String id);

2 – As a method parameter when the param may be null:

public Foo doSomething(String id, Optional<Bar> barOptional);

3 – As an optional member of a bean:

public class Book {

  private List<Pages> pages;
  private Optional<Index> index;

}

4 – In Collections:

In general I don’t think:

List<Optional<Foo>>

adds anything – especially since one can use filter() to remove null values etc, but are there any good uses for Optional in collections?

Any cases I’ve missed?

14 Answers
14

Leave a Comment