pjanssen pjanssen - 7 months ago 65
Java Question

java streaming parent and children into one list

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())

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<Child> allChildren = parents.stream()
    .flatMap(p -> Stream.concat(Stream.of(p), p.getChildren().stream()))