flatMap in Java 8

flatMap in Java 8 (as described in the below figure) lets you replace a value with a Stream and concatenates all the streams together. You’ve already seen the map operation in this article, which replaces a value in a Stream with a new value. Sometimes you want a variant of map in which you produce a new Stream object as the replacement. Frequently you don’t want to end up with a stream of streams, though, and this is where flatMap comes in handy. 

Let’s look at a simple example. We’ve got a Stream of Lists of numbers, and we want all the numbers from these in a sequences. We can solve this problem using the following approach.

Stream list List<Integer> together = Stream.of(asList(1, 2), asList(3, 4))
  .flatMap(numbers -> numbers.stream()).collect(toList());
assertEquals(asList(1, 2, 3, 4), together); 

We replaced the List with a Stream using the stream method, and flatMap does the rest. Its associated functional interface is the same as map’s—the Function —but its return type is restricted to streams and not any value.