[英]I have a nested object structure. I want to create a list of object picking attributes from the nested object using streams in Java
// input
public class A {
int a1;
String a2;
int a3;
String a4;
Object B;
}
public class B {
List<Object> C;
}
public class C {
int c1;
Date d;
List<E> e;
}
public class E {
int e1;
int e2;
}
---------------------------------------
// output
public class H {
int a1;
String a2;
int a3;
String a4;
int c1;
Date d;
int e1;
int e2;
}
上面(对象A)是我拥有的嵌套object的结构。 我想创建一个 Object H 列表,如上所述选择属性。 我可以使用传统的嵌套 for 循环来做到这一点,但最好使用流寻找更优化和更清洁的东西。
function 的输入将是List<A>
和 output 应该是List<H>
。
Recommend taking a look at some guides or examples for Java stream such as https://mkyong.com/java8/java-8-streams-map-examples/ or https://www.baeldung.com/java-8-streams .
您可以创建一个转换器 function 并使用 Stream::map()。
public List<H> convert(List<A> listOfA) {
return listOfA.stream().map(this::convert).collect(Collectors.toList());
}
public H convert(A a) {
// Create a new H.
// Extract attributes from A and set in H.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.