Quiz: Java Stream flatMap and Stream.concat: Flattening and Combining Streams
Study the lesson first: Java Stream flatMap and Stream.concat: Flattening and Combining Streams
Total: 7 questions
1. What does flatMap() do in the Java Stream API, and how is it different from map()?
What does flatMap() do in the Java Stream API, and how is it different from map()?
flatMap() is a stateless intermediate Stream API operation (Java 8): the mapper function turns every element into a stream of zero, one or many elements, and those streams are joined into one flat Stream<R>. Signature: <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper).
The difference from map() is what the function returns:
map(): the function returns a single valueR, and there are exactly as many output elements as input ones. If the function returns a list, an array or a stream, the result becomes nested:Stream<List<T>>,Stream<String[]>,Stream<Stream<T>>.flatMap(): the function returns a stream, one input element produces 0, 1 or N output elements, and there is no nesting.
Example: for List.of("Java is fun", "Streams are lazy"), map(s -> s.split(" ")) gives 2 arrays, while flatMap(s -> Arrays.stream(s.split(" "))) gives 6 words. flatMap(s -> s.split(" ")) does not compile: the array has to be wrapped in Arrays.stream(). A typical mistake is map(s -> Arrays.stream(...)): the code compiles, but printing shows java.util.stream.ReferencePipeline$Head@... instead of words, because every element is a whole stream.
2. How do you flatten a list of lists into one list with flatMap(), and what other common flatMap() patterns are used in practice?
How do you flatten a list of lists into one list with flatMap(), and what other common flatMap() patterns are used in practice?
A list of lists into one list: nested.stream().flatMap(List::stream).toList() - for [[1, 2], [3], [], [4, 5]] you get [1, 2, 3, 4, 5]; an empty inner list simply adds nothing. The other frequent patterns:
- Nested collections of objects:
orders.stream().flatMap(order -> order.items().stream())- all line items of all orders (the example from the JDK Javadoc). - Map values:
map.values().stream().flatMap(Collection::stream); for key-value pairs -map.entrySet().stream().flatMap(e -> e.getValue().stream().map(v -> e.getKey() + "=" + v)): the key is available because a nested stream is created for each entry. - A two-dimensional array of objects:
Arrays.stream(table).flatMap(Arrays::stream). - Characters of strings:
flatMapToInt(String::chars)-chars()returns anIntStream, not aStream<Character>. - Dropping empty Optionals:
flatMap(Optional::stream)(Java 9+) instead offilter(Optional::isPresent).map(Optional::get).
When the flattening has to happen inside a grouping (all skills per department), you use the Collectors.flatMapping() collector (Java 9) as a downstream of groupingBy() rather than flatMap().
3. Why do flatMapToInt(), flatMapToLong() and flatMapToDouble() exist, and how are they different from IntStream.flatMap()?
Why do flatMapToInt(), flatMapToLong() and flatMapToDouble() exist, and how are they different from IntStream.flatMap()?
The function of a regular Stream.flatMap() must return a Stream, yet many sources of primitive values return primitive streams: Arrays.stream(int[]) and String.chars() return an IntStream. Hence:
Stream.flatMapToInt()/flatMapToLong()/flatMapToDouble()- called on an object stream, the function returns anIntStream/LongStream/DoubleStream, and the result is a primitive stream. Example: the sum of all numbers in anint[][]-Arrays.stream(matrix).flatMapToInt(Arrays::stream).sum().IntStream.flatMap()(and the ones onLongStream,DoubleStream) - called on a primitive stream and returns a stream of the same type:IntStream.rangeClosed(1, 3).flatMap(n -> IntStream.range(0, n))gives0, 0, 1, 0, 1, 2.mapMultiToInt()/mapMultiToLong()/mapMultiToDouble()(Java 16) - the same through anIntConsumerinstead of returning a stream.
For an int[][], flatMap(Arrays::stream) does not compile. If you really need a Stream<Integer>, write flatMap(row -> Arrays.stream(row).boxed()).
4. How does flatMap() treat nested streams: does it close them, what happens with null, does it work with infinite streams, and does it keep the order?
How does flatMap() treat nested streams: does it close them, what happens with null, does it work with infinite streams, and does it keep the order?
- Closing: every nested stream is closed right after its elements have been passed downstream, not at the end of the pipeline. So
paths.stream().flatMap(path -> Files.lines(path))closes each file as soon as it has been read. - null: if the function returns
null, an empty stream is used - the element just disappears, noNullPointerException. Do not rely on it:Stream.empty()is clearer. - Laziness: since Java 10 nested streams are read lazily, and
findFirst(),limit(),anyMatch()stop even an infinite nested stream:Stream.of("a", "b").flatMap(s -> Stream.generate(() -> s)).limit(3)gives[a, a, a]. In Java 8 and 9 a nested stream was drained completely (bug JDK-8075939), and such code never finished. - Order: for an ordered stream all elements of the first nested stream come first, then the second, and so on. In a parallel stream
toList(),collect()andforEachOrdered()keep the order, butforEach()does not.
5. What is mapMulti() in Java 16, and when is it better than flatMap()?
What is mapMulti() in Java 16, and when is it better than flatMap()?
mapMulti() (Java 16) performs the same "one element to zero or more" transformation as flatMap(), but the function does not return a stream: it receives the element and a Consumer and passes results through accept() calls. Signature: <R> Stream<R> mapMulti(BiConsumer<? super T, ? super Consumer<R>> mapper); for primitives there are mapMultiToInt/Long/Double().
According to the Javadoc it is preferable to flatMap() in two cases:
- each element is replaced by a small number of elements, often zero or one -
flatMap()creates a newStreamobject per element,mapMulti()does not. Example: keep only theIntegervalues of aStream<Number>- filter and cast in one step; - the result is easier to produce imperatively - with conditions, loops, recursion (for example, expanding nested lists of any depth).
Details: the compiler cannot infer the result type (the lambda has no return), so you write stream.<Integer>mapMulti(...) - without it you get a Stream<Object>. The Consumer may be called only while the function is running. If flattening needs state across elements (batches, windows), neither flatMap() nor mapMulti() fits - that is a job for gather() from Java 24.
6. How do you combine two streams in Java with Stream.concat(), and what are the properties of the result?
How do you combine two streams in Java with Stream.concat(), and what are the properties of the result?
Stream.concat(a, b) is a static method (Java 8) that returns a new stream: all elements of a first, then all elements of b. Merging two lists: Stream.concat(list1.stream(), list2.stream()).toList(), without duplicates - add distinct(). For primitives there are IntStream.concat(), LongStream.concat(), DoubleStream.concat().
Properties of the result according to the Javadoc:
- lazy: elements are not copied into a collection but read as needed; if the first stream is infinite, the second one never starts;
- ordered only if both streams are ordered; parallel if at least one of them is parallel;
- closing the result runs the close handlers of both streams - try-with-resources on the result is enough;
- both streams are bound to their source at call time:
aandbmust not be used afterconcat(), and passing the same stream again throwsIllegalStateExceptionright at theconcat()call; - it takes exactly two arguments.
If you simply need a mutable combined list, new ArrayList<>(a) plus addAll(b) is simpler; concat() wins when the merge is part of a pipeline with filter(), map(), sorted(). Note that toList() returns an unmodifiable list.
7. How do you combine three or more streams or lists, and why should you not build nested Stream.concat() calls in a loop?
How do you combine three or more streams or lists, and why should you not build nested Stream.concat() calls in a loop?
The Stream.concat() Javadoc recommends building a stream of streams and flattening it: Stream.of(s1, s2, s3).flatMap(Function.identity()) (or flatMap(s -> s)). For lists - Stream.of(list1, list2, list3).flatMap(List::stream).toList(), and if the lists already sit in a List<List<T>> - lists.stream().flatMap(List::stream).toList().
Stream.concat(Stream.concat(s1, s2), s3) works for three streams, but a chain like result = Stream.concat(result, next) in a loop or reduce(Stream.empty(), Stream::concat) builds deep nesting. Each concat() wraps the previous result, and reaching an element means descending through every level:
- with many streams you get a
StackOverflowError(the@implNotein the Javadoc warns about it). The threshold depends on the stack size (-Xss) and the JVM: in a thread with a 256 KB stack 1,000 nestedconcat()calls pass, while 10,000 already fail; - even earlier you notice the quadratic growth of the running time.
The flatMap() version does not depend on depth: the streams are processed one after another instead of being nested inside each other. So merging results across a list of files, API pages or partitions should be written with a list of streams and flatMap() from the start.