简体   繁体   中英

Java8 lambda nested null check

Currently I am using Optional value in following format: Is there a way to reduce code further ?

final Optional<List<ServiceAttributeValue>> attributeValueList = Optional.<Product> of(product)
         .map(Product::getServiceAttributes)
         .map(ServiceAttributeMap::getMap)
         .map((v) -> (ServiceAttribute) v.get(attributeV.getAttributeString()))
         .map((c) -> (List<ServiceAttributeValue>) c.getValueList());

if (!attributeValueList.isPresent()) {
    return null;
}

final Optional<ServiceAttributeValue> value = attributeValueList.get().stream()
         .filter((attribute) -> StringUtils.equals(attribute.getFoo(), attributeV.getBar()))
         .findFirst();

if (value.isPresent()) {
     return value.get().bar();
}

return null;

At first, you should avoid return null , if you're already using Optional . Instead, an empty Optional should indicate, that the element is missing.

Optional::map will only map the value, if it is present. So instead of checking, if the value isPresent and then retrunging null , you can simplify this to

attributeValueList.flatMap(values -> values.stream().filter((attribute) -> StringUtils.equals(attribute.getFoo(), attributeV.getBar()).findFirst())
...

You can also apply this to the second isPresent check, when you change it to

return value.map(x -> x.bar());

All together could look like this (not tested, since I don't know the classes):

return Optional.<Product>of(product)
        .map(Product::getServiceAttributes)
        .map(ServiceAttributeMap::getMap)
        .map((v) -> (ServiceAttribute) v.get(attributeV.getAttributeString()))
        .map(c::getValueList)
        .flatMap(values -> values
            .stream()
            .filter((attribute) -> StringUtils.equals(attribute.getFoo(), attributeV.getBar()))
            .findFirst())
        .map(x -> x.bar());

The positive effect of this is, that your function returns an empty Optional , when one of the steps did not return anything. All other steps are ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM