如何用Java Stream API实现嵌套对象数据提取并生成List<D>
原提问内容
问题描述
在架构中存在需结构化展示的数据对象,结构如下:
public class A { private final String a1; public A( String a1 ) { this.a1 = a1; } public String getA1() { return a1; } }
public class B { private final String b1; private final List<A> bList; public B( String b1, List<A> list ) { this.b1 = b1; this.bList = list; } public String getB1() { return b1; } public List<A> getBList() { return bList; } }
public class C { private final String c1; private final int c2; private final List<B> cList; public C( String c1, int c2, List<B> list ) { this.c1 = c1; this.c2 = c2; this.cList = list; } public String getC1() { return c1; } public int getC2() { return c2; } public List<B> getCList() { return cList; } }
对象C包含若干值及B对象列表,B对象包含自身值及A对象列表,A对象也包含自身值。需求分为两点:
- 转换为JSON结构
- 生成包含所有数据属性的D对象列表,D类定义如下:
public class D { public final String a1; public final String b1; public final String c1; public final int c2; public D( String a1, String b1, String c1, int c2 ) { this.a1 = a1; this.b1 = b1; this.c1 = c1; this.c2 = c2; } }
目标为获取List<D>。
当前方案
已用Jackson完成JSON转换:
C c = someGetterForC(); ObjectMapper mapper = new ObjectMapper(); mapper.enable( SerializationFeature.INDENT_OUTPUT ); try { return mapper.writeValueAsString( c ); } catch( JsonProcessingException e ) { // do error handling here }
生成List<D>目前用嵌套for循环实现:
List<D> dList = new ArrayList<>(); C c = someGetterForC(); for( B b : c.getCList() ) { for( A a : b.getBList() ) { D d = new D( a.getA1(), b.getB1(), c.getC1(), c.getC2() ); dList.add( d ); } }
疑问
希望用Java Stream API实现List<D>生成,但存在两个难点:
- 流式处理B列表后如何继续处理A列表
- 同一流式调用中访问A、B、C的非列表成员并生成D对象
能否通过单次Stream API调用实现?若可以,是否具备合理性?
说明
- 必须使用Java 11,无法使用更高版本数据结构
- D对象存在冗余数据是预期且可接受的
示例
假设C对象c_alpha:
c1 = "car" c2 = 42; cList = {b_alpha, b_beta}
B对象b_alpha:
b1 = "boulder" bList = {a_alpha}
B对象b_beta:
b1 = "bomb" bList = {a_beta, a_gamma}
A对象a_alpha:
a1 = "ape"
A对象a_beta:
a1 = "andromeda"
A对象a_gamma:
a1 = "axe"
预期List<D>:
{ new D("ape", "boulder", "car", 42), new D("andromeda", "bomb", "car", 42), new D("axe", "bomb", "car", 42) }
总结
针对含基本类型、字符串及嵌套对象列表的Java对象,如何通过单次Stream API调用提取所有层级数据生成元组列表?
内容的提问来源于stack exchange,提问作者Koenigsberg
相关产品推荐
相关产品推荐

