Search code examples
javaoption-type

How to get value from an optional object in another optional?


Basically,I need to get a size of optional list in an optional object. Something like:

private int getCount(@NonNull Optional<myObject> aaa) {
    if(aaa.isPresent() && aaa.get().getMyList().isPresent()) {
        return aaa.get().getMyList().get().size();
    }

    return 0;
}

The code doesn't look nice. What's the elegant way to get it? With ifPresent().orElse()? Thanks in advance!


Solution

  • Consecutive map (or flatMap, in case something returns an Optional) operations, and a final orElse:

    private int getCount(@NonNull Optional<myObject> cvm) {
        return cvm
          .flatMap(x -> x.getMyList())
          .map(list -> list.size()) // or List::size
          .orElse(0);
    }