如何使用Stream API从对象检索嵌套列表? [英] How to retrieve nested list from object using Stream API?

查看:100
本文介绍了如何使用Stream API从对象检索嵌套列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您是否知道如何从TopComplexity对象中检索所有SimpleProperty? 我需要将该 for循环更改为种类"一段代码.

Do you have any idea how to retrieve all SimpleProperty from TopComplexity object? I need to change that for loop into stream "kind" piece of code.

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

真的很感谢任何帮助

推荐答案

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

You can mix up flatMap with a concatenation and ternary operator involving Streams such as:

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

这篇关于如何使用Stream API从对象检索嵌套列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆