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)
)))
The code to flatten the List
:
List<Employee> total =
emps.stream()
.flatMap(emp -> emp.members.stream())
.collect(Collectors.toList());
The total
List
should have 3 elements, but it only has 2.
Eran's answer is wrong, there is no concat
on Stream
instance. This should work:
emps.stream()
.flatMap(emp -> Stream.concat(emp.members.stream(), Stream.of(emp)))
.collect(Collectors.toList());
Stream#concat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With