Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a List of lists using Streams in this specific case?

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?

like image 894
inis bali Avatar asked May 30 '18 12:05

inis bali


People also ask

How can I turn a List of lists into a List in Java 8?

Here is the simple, concise code to perform the task. // listOfLists is a List<List<Object>>. List<Object> result = new ArrayList<>(); listOfLists. forEach(result::addAll);

How do you collect a stream from an ArrayList?

All you need to do is first get the stream from List by calling stream() method, then call the filter() method to create a new Stream of filtered values and finally call the Collectors. toCollection(ArrayList::new) to collect those elements into an ArrayList.


1 Answers

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());
like image 143
Eran Avatar answered Sep 23 '22 18:09

Eran