Home > Net >  Is there a way to go through inner objects with less verbosity
Is there a way to go through inner objects with less verbosity

Time:07-09

I'm needing to through some inner objects like this (I always need the index 0):

e1.getElements().get(0).getVariantOption().getPointOfServices().sort(comparator);

I'm checking all empty list and nulls with this piece of code.

if (CollectionUtils.isNotEmpty(e1.getElements()) && e1.getElements().get(0).getVariantOption() != null &&
            CollectionUtils.isNotEmpty(e1.getElements().get(0).getVariantOption().getPointOfServices()))
    {
        e1.getElements().get(0).getVariantOption().getPointOfServices().sort(comparator);
    }

Is there a way in Java to reach this same without repeating all that times the e1.getElements...? I feel like this code is pretty verbose.

CodePudding user response:

It can be simplified to this:

VariantOption option = CollectionUtils.isNotEmpty(e1.getElements()) ? 
                    e1.getElements().get(0).getVariantOption() : null;

if (option != null && CollectionUtils.isNotEmpty(option.getPointOfServices()))
{
    option.getPointOfServices().sort(comparator);
}

I assumed getVariantOption function to return an object of class VariantOption, but modify it accordingly.

  •  Tags:  
  • java
  • Related