Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading