Sobes.tech
Junior — Middle

In what cases should you use the flatMap method in collection processing?

sobes.tech AI

Answer from AI

The flatMap method is used when you need to process a collection whose elements are themselves collections (or optional values), and you want to obtain a single flat stream of elements from them.

For example, if you have a list of lists and want to get a single list of all elements, not a list of lists.

Example:

List<List<String>> listOfLists = Arrays.asList(
    Arrays.asList("a", "b"),
    Arrays.asList("c", "d")
);

List<String> flatList = listOfLists.stream()
    .flatMap(Collection::stream) // convert Stream<List<String>> to Stream<String>
    .collect(Collectors.toList());

// flatList will contain: ["a", "b", "c", "d"]

Thus, flatMap helps to "flatten" nested structures and work with elements as a single stream.