Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java8 lambda嵌套空检查_Java_Lambda_Java 8_Optional - Fatal编程技术网

Java8 lambda嵌套空检查

Java8 lambda嵌套空检查,java,lambda,java-8,optional,Java,Lambda,Java 8,Optional,目前我正在使用以下格式的可选值: 有没有办法进一步减少代码 final Optional<List<ServiceAttributeValue>> attributeValueList = Optional.<Product> of(product) .map(Product::getServiceAttributes) .map(ServiceAttributeMap::getMap) .map((v)

目前我正在使用以下格式的可选值: 有没有办法进一步减少代码

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;

首先,如果您已经在使用Optional,那么应该避免返回null。相反,一个空的可选项应该指示缺少元素

可选::map仅映射值(如果存在)。 因此,如果值为present,然后重新运行null,而不是检查, 您可以将此简化为

attributeValueList.flatMap(values -> values.stream().filter((attribute) -> StringUtils.equals(attribute.getFoo(), attributeV.getBar()).findFirst())
...
当您将第二个iPresent检查更改为时,也可以将其应用于第二个iPresent检查

return value.map(x -> x.bar());
由于我不知道这些类别,所有这些可能看起来都没有经过测试:

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

这样做的积极效果是,当其中一个步骤没有返回任何内容时,函数返回一个空的可选值。所有其他步骤都被忽略。

谢谢,对于line filter和findFirstSorry,给定的语法无法为我编译,只是看到您在其中使用了一个集合。我更改了代码,也许您可以再次检查itr。我建议为产品添加一个新方法:StreamServiceAttributeValue字符串属性或serviceAttributeString属性(如果使用频率更高)。不管怎样,我想知道这些值中哪一个实际上可以为null。显然不是产品,也不是ServiceAttributeMap::getMap的返回值。甚至可能不是Product::getServiceAttributes,也肯定不是c.getValueList。这只会给我们留下v.get和大量开销。