是否有一种方法可以更少地遍历内部对象



我需要通过一些内部对象,像这样(我总是需要索引0):

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

我用这段代码检查所有的空列表和null。

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

是否有一种方法在Java中达到相同的,而不重复所有的时间e1.getElements…?我觉得这段代码太啰嗦了。

可以简化为:

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

我假设getVariantOption函数返回一个类VariantOption的对象,但对它进行了相应的修改。

最新更新