问题
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 Stream
s 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