'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 1:[1]

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);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1