TL;DR: turn a list of parents with children into a list of persons using java streaming api.
Let's assume the following classes:
public abstract class Person {
private String name;
}
public class Parent extends Person {
List<Children> children;
}
public class Child extends Person {
int age;
}
The following code would give me a list of all children
List<Child> allChildren = parents.stream()
.flatMap(p -> p.getChildren().stream())
.collect(Collectors.toList());
I like to get a list of all persons so including parents. Is this at all possible with java 8 streaming?
You can add the parents to the stream using Stream::concat
:
List<Person> persons = parents.stream()
.flatMap(p -> Stream.concat(Stream.of(p), p.getChildren().stream()))
.collect(Collectors.toList());
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