Home > Back-end >  How to get value from an optional object in another optional?
How to get value from an optional object in another optional?

Time:03-22

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!

CodePudding user response:

Consecutive map operations, and a final orElse:

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