pjanssen pjanssen - 1 year ago 113
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?

Answer Source

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()))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download