我有一些类似下面的类:
Class A {
private String name;
private List<B> b;
// getters and setters
}
Class B {
private String name;
private List<C> c;
// getters and setters
}
Class C {
private String name;
private List<D> d;
// getters and setters
}
Class D {
// properties
// getters and setters
}
现在我有一个type列表A
。我想要做的是获取包含其他类型的列表的列表,D
如下所示:
List<List<D>>
我已经尝试过使用这样的东西flatMap
:
listA.stream()
.flatMap(s -> s.getB.stream())
.flatMap(s -> s.getC.stream())
.flatMap(s -> s.getD.stream())
.collect(Collectors.toList());
但这会将类型的所有元素收集D
到一个列表中:
List<D>
有人可以帮忙吗?
如果您想要List<List<D>>
一个,则少用一个flatMap
:
List<List<D>> ds = listA.stream() // creates Stream<A>
.flatMap(s -> s.getB().stream()) // creates Stream<B>
.flatMap(s -> s.getC().stream()) // creates Stream<C>
.map(s -> s.getD()) // creates Stream<List<D>>
.collect(Collectors.toList());
要么
List<List<D>> ds = listA.stream() // creates Stream<A>
.flatMap(s -> s.getB().stream()) // creates Stream<B>
.flatMap(s -> s.getC().stream()) // creates Stream<C>
.map(C::getD) // creates Stream<List<D>>
.collect(Collectors.toList());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句