4

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?

1 Answer 1

7

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, very simple. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.