Sobes.tech
Junior — Middle

What is the purpose of the flatMap method in the Stream API for data processing?

sobes.tech AI

Answer from AI

The flatMap method in Stream API is used to transform each element of the source stream into a new stream, and then flatten (concatenate) all these streams into a single stream. It is useful when each element can correspond to multiple elements in the resulting stream.

For example, if you have a list of strings and want to get a stream of all characters from all strings, you can use flatMap:

List<String> words = List.of("hello", "world");
List<Character> chars = words.stream()
    .flatMap(word -> word.chars().mapToObj(c -> (char) c))
    .collect(Collectors.toList());

Here, flatMap transforms each word into a stream of characters, then combines all these streams into one.

Thus, flatMap helps work with nested data structures and simplifies their processing as a flat stream.

What is the purpose of the flatMap method in the… - sobes.tech