[英]How to retrieve nested list from object using Stream API?
Do you have any idea how to retrieve all SimpleProperty
from TopComplexity
object?您知道如何从TopComplexity
object 中检索所有SimpleProperty
吗? I need to change that for loop into stream "kind" piece of code.我需要将for 循环更改为stream “种类”代码。
@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非常感谢任何形式的帮助
You can mix up flatMap
with a concatenation and ternary operator involving Stream
s such as:您可以将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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.