Java Streams and flatMap
Stream flatMap replaces each element with a stream and joins all those streams into one. A list of sentences can therefore become one flat stream of words.
map keeps a stream of lists
map turns each sentence into a list of its words. The stream stays a stream of lists, and each printed line keeps its brackets.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> sentences = List.of("the cat sat", "a dog ran");
sentences.stream()
.map(sentence -> Arrays.asList(sentence.split(" ")))
.forEach(System.out::println);
}
}flatMap gives one flat stream of words
flatMap kept an Optional chain flat in the previous lesson. Here the same flattening joins each word stream into one stream, so each word prints on its own line.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> sentences = List.of("the cat sat", "a dog ran");
sentences.stream()
.flatMap(sentence -> Arrays.stream(sentence.split(" ")))
.forEach(System.out::println);
}
}A second flattening gives letters
A stream of words can flatten one level further. Each word becomes a stream of its letters, and the letters print one per line.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("cat", "dog");
words.stream()
.flatMap(word -> Arrays.stream(word.split("")))
.forEach(System.out::println);
}
}Example
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> sentences = List.of("Java streams flow", "Code stays flat");
List<String> words = sentences.stream()
.flatMap(sentence -> Arrays.stream(sentence.split(" ")))
.toList();
words.forEach(System.out::println);
System.out.println("Words: " + words.size());
}
}Key points
- map gives one output for each input, even when that output is a whole list.
- flatMap replaces each element with a stream and joins those streams into one stream.
- split returns an array of words, and Arrays.stream turns that array into the inner stream.
- Flattening can chain, so a stream of words can flatten again into a stream of letters.
- Use flatMap when the data already sits in groups and the next step needs the items themselves.
In this example, flatMap turns two sentences into one list of six words. Each word prints on its own line, and the final line counts the words in the flat list.
Note
The function passed to flatMap must return a stream for each element.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A stream holds one list per sentence, and the next step needs single words. Which operation flattens the stream?