class Employee {
private String name;
private List<Employee> members;
}
List<Employee> emps = Arrays.asList(new Employee("A", Arrays.asList(
new Employee("B", null),
new Employee("C", null)
)))
Run Code Online (Sandbox Code Playgroud)
用于展平的代码List:
List<Employee> total =
emps.stream()
.flatMap(emp -> emp.members.stream())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
本total List应该有3个要素,但只有2个。
伊兰的答案是错的,也没有concat在Stream实例。这应该有效:
emps.stream()
.flatMap(emp -> Stream.concat(emp.members.stream(), Stream.of(emp)))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |