小编典典

如何使用Stream API从对象检索嵌套列表?

java

您有任何想法如何SimplePropertyTopComplexity对象中检索全部吗?我需要将 for循环 更改为
“同类”代码。

@Data
public class TopComplexity {
   List<SuperComplexProperty> superComplexProperties;
}
@Data
public class SuperComplexProperty {
   List<SimpleProperty> simpleProperties;
   ComplexProperty complexProperty;
}

@Data
public class ComplexProperty {
   List<SimpleProperty> simpleProperties;
}

public class MainClass {
   public static void main(String[] args) {

       TopComplexity top = null;
       List<SimpleProperty> result = new ArrayList<>();

       for(SuperComplexProperty prop : top.getSuperComplexProperties) {
          result.addAll(prop.getSimpleProperties());

          if(Objects.nonNull(prop.getComplexProperty()) {
              result.addAll(prop.getComplexProperty().getSimpleProperties());
         }
      }
   }
}

非常感谢任何帮助


阅读 294

收藏
2020-11-26

共1个答案

小编典典

您可以flatMap与涉及Stream的串联和三元运算符混合使用,例如:

List<SimpleProperty> result = top.getSuperComplexProperties().stream()
        .flatMap(scp -> Stream.concat(
                scp.getSimpleProperties().stream(),
                scp.getComplexProperty() == null ?
                        Stream.empty() :
                        scp.getComplexProperty().getSimpleProperties().stream()))
        .collect(Collectors.toList());
2020-11-26