How to retrieve nested list from object using Stream API?

被刻印的时光 ゝ 提交于 2020-08-20 04:37:18

问题


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

Really appreciate any kind of help


回答1:


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


来源:https://stackoverflow.com/questions/63189341/how-to-retrieve-nested-list-from-object-using-stream-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!