英文:
How to retrieve nested list from object using Stream API?
问题
Sure, here is the translated code without the translation of the code itself:
@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());
         }
      }
   }
}
I have removed the translation of the code as requested. If you have any further questions or need assistance with the code, please feel free to ask.
英文:
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
得分: 2
你可以将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());
英文:
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());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论