Saturday 26 August 2023

Tricky question

 

In a social media application, You have a collection of posts, where each post can have multiple comments. 

To retrieve all the comments from all the posts and represents them as a single stream,
Which java Stream operation would you use?

 

The correct answer is flatmap().

So what is flatmap, flatMap() = Flattening + map()

It is an intermediate operation that is always lazy as described in Java Stream API

flattening means,  merging multiple collections/arrays into one.

OR,

Flattening is the process of converting several lists of lists and merge all those lists to create a single list containing all the elements from all the lists.

Flattening Example

Consider the following lists of lists:

Before Flattening: [[1, 2, 3, 4], [7, 8, 9, 0], [5, 6], [12, 18, 19, 20, 17], [22],[23,24,25,26,27]]

After Flattening: [1, 2, 3, 4, 7, 8, 9, 0, 5, 6, 12, 18, 19, 20, 17, 22,23,24,25,26,27]

Syntax

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)


  • R represents the element type of the new stream.
  • mapper is a non-interfering, stateless function to apply to each element which produces a stream of new values.
  • The method returns a new stream of objects of type R.

Similar flatMap() Methods

IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)

Some examples where flatMap can be used are:
Count of words of a text file.
Convert a Nested List into a single List.
Convert a Nested Array into a single Lis