Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating lists using flatMap

I'm reading a Java 8 book by Ricahrd Warburton and he provided the following excercise:

try rewriting the following using method references:

[...]

The flatMap approach to concatenate lists

I really don't understand how to apply flatMap here. The thing that confused me was that flat map is used to map each element of a Stream to another Stream and then concatenate them together to produce a larger Stream but here we have to separate List<T>.

public static <T> List<T> concat(List<T> lst1, List<T> lst2){
    //lst1.stream().flatMap() - it maps each elements 
                                //of lst1 to stream and concatenates it for each                                          
                                //element    
}

Any ideas?

like image 659
stella Avatar asked Oct 27 '25 04:10

stella


1 Answers

For the purpose of the exercise, the idea is to use Stream.of(...) to create a Stream<List<T>> containing the two given lists, and flat map each list with the method reference List::stream. This will flatten the Stream<List<T>> into a Stream<T>. Then, you can collect all the elements into a list with Collectors.toList():

public static <T> List<T> concat(List<T> lst1, List<T> lst2){
    return Stream.of(lst1, lst2).flatMap(List::stream).collect(Collectors.toList());
}
like image 144
Tunaki Avatar answered Oct 29 '25 19:10

Tunaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!