您有任何想法如何SimpleProperty从TopComplexity对象中检索全部吗?我需要将 for循环 更改为 流 “同类”代码。
SimpleProperty
TopComplexity
@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的串联和三元运算符混合使用,例如:
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());