5

I have some classes like below:

Class A {
    private String name;
    private List<B> b;
    // getters and setters
}
Class B {
    private String name;
    private List<C> c;
    // getters and setters
}
Class C {
    private String name;
    private List<D> d;
    // getters and setters
}
Class D {
    // properties
    // getters and setters
}

Now I have a list of type A. What I want to do is to get a list containing other lists of type D like this:

List<List<D>>

I have tried somthing like this using flatMap:

listA.stream()
     .flatMap(s -> s.getB.stream())
     .flatMap(s -> s.getC.stream())
     .flatMap(s -> s.getD.stream())
     .collect(Collectors.toList());

But this collects all the elements of type D into a list:

List<D>

Can someone help please?

Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
inis bali
  • 71
  • 4
  • You can use flatMap to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list – surendrapanday May 30 '18 at 13:03
  • Check here. https://stackoverflow.com/questions/25147094/how-can-i-turn-a-list-of-lists-into-a-list-in-java-8?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – surendrapanday May 30 '18 at 13:06

1 Answers1

7

If you want a List<List<D>> you need one less flatMap:

List<List<D>> ds = listA.stream() // creates Stream<A>
                        .flatMap(s -> s.getB().stream()) // creates Stream<B>
                        .flatMap(s -> s.getC().stream()) // creates Stream<C>
                        .map(s -> s.getD()) // creates Stream<List<D>>
                        .collect(Collectors.toList());

or

List<List<D>> ds = listA.stream() // creates Stream<A>
                        .flatMap(s -> s.getB().stream()) // creates Stream<B>
                        .flatMap(s -> s.getC().stream()) // creates Stream<C>
                        .map(C::getD) // creates Stream<List<D>>
                        .collect(Collectors.toList());
Eran
  • 387,369
  • 54
  • 702
  • 768