ini*_*ali 5 java grouping list java-8 java-stream
我有一些类如下:
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
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个类型列表A.我想要做的是获得一个包含其他类型列表的列表,D如下所示:
List<List<D>>
Run Code Online (Sandbox Code Playgroud)
我尝试过这样的事情flatMap:
listA.stream()
.flatMap(s -> s.getB.stream())
.flatMap(s -> s.getC.stream())
.flatMap(s -> s.getD.stream())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
但是这会将类型的所有元素收集D到一个列表中:
List<D>
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
如果你想要一个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());
Run Code Online (Sandbox Code Playgroud)
要么
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());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
157 次 |
| 最近记录: |