Course contentsShow
← Java
Lesson 1440 of 2,87032. Streams API: Intermediate OperationsFree lesson

Splitting Strings with flatMap

Using flatMap with String.split to transform sentences into individual words.

Splitting Strings with flatMap

What you'll learn: How to use flatMap with String.split() to break sentences or lines of text into streams of individual words.

The Core Idea

When you have a stream of strings (like sentences or lines from a file), and you want to process individual words rather than entire strings, flatMap combined with String.split() is your solution. Each sentence produces an array of words, and flatMap flattens those arrays into a single continuous stream of words.

How It Works

The String.split() method takes a string and returns an array of substrings. When you use it inside flatMap, you need to convert that array into a stream using Arrays.stream(). The flatMap operation then merges all these word streams into one.

Basic Pattern

Stream<String> sentences = Stream.of(
    "Java streams are powerful",
    "flatMap enables flattening",
    "Split creates word arrays"
);

Stream<String> words = sentences
    .flatMap(sentence -> Arrays.stream(sentence.split(" ")));

words.forEach(System.out::println);
// Output: Java, streams, are, powerful, flatMap, enables, flattening, Split, creates, word, arrays

Why Not Just map?

If you used map with split(), you'd get a Stream<String[]> — a stream of arrays. That's not what you want! You want a stream of individual strings. flatMap unwraps those arrays into a single flat stream.

Practical Use Case

This pattern is essential for text processing tasks like word counting, searching for specific words across multiple lines, or analyzing text files.

Key Takeaway: Use flatMap with String.split() to transform a stream of sentences into a stream of individual words by flattening the resulting arrays.