Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
pjanssen Avatar asked Oct 25 '16 08:10

pjanssen


1 Answers

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());
like image 64
assylias Avatar answered Sep 19 '22 05:09

assylias