Junior — Middle
Can you show an example of using the flatMap method in Stream API for collection processing?
sobes.tech AI
Answer from AI
The flatMap method in the Stream API is used to transform each element of a stream into another stream and then merge all these streams into one.
This is useful when you have a collection of collections and want to get a single flat stream of all elements.
Example: there is a list of lists of strings, and you want to get a single list of all strings:
import java.util.*;
import java.util.stream.*;
public class FlatMapExample {
public static void main(String[] args) {
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("apple", "banana"),
Arrays.asList("orange", "pear"),
Arrays.asList("grape")
);
List<String> flatList = listOfLists.stream()
.flatMap(Collection::stream) // transform each inner list into a stream and merge
.collect(Collectors.toList());
System.out.println(flatList); // [apple, banana, orange, pear, grape]
}
}
Here, flatMap flattens nested lists into a single stream of elements.