pjanssen pjanssen - 1 month ago 19
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())
.collect(Collectors.toList());


I like to get a list of all persons so including parents. Is this at all possible with java 8 streaming?

Answer

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()))
    .collect(Collectors.toList());
Comments