Interviewer: what is the difference between Java 8 map and flatMap? Most people can't answer!


The stack leader often asks the difference between Java 8 map and FlatMap in the interview. Most people can't answer, and few people can use map. Some people don't even know what these two things are used for. Some thought I asked HashMap and FlatMap..

The map and flatMap asked here are not collections. They are all methods in the Stream interface. If you haven't used them, I guess everyone here is a little dizzy. Today, the stack leader will sweep your blindness and analyze these two things with actual cases, so that you won't be afraid to ask again during the interview!

As shown in the figure:

There are eight particularly interesting methods in the Java 8 Stream interface, which are actually divided into two categories:

  • map
  • flatMap

Now you know where these two things come from?!

Among them, xxtoxx is a stream converted to different types. In addition, I have written a topic before Stream series, and I will not focus on the Java stack of official account, and then read it in the official account Java tutorial menu.


Function of map method:

Convert each element in the stream

For example, there is a list < string > Set:

private static List<String> LIST = Arrays.asList("https://", "www", ".", "javastack", ".", "cn");

I want to add "---" after each element:

 * map transformation
 * @author: Stack length
 * @from: Official account Java technology stack
private static void map() {
    List<String> mapList = -> e.concat("---")).collect(Collectors.toList());
    System.out.println("\nmap list size: " + mapList.size());

1) First convert the List to Stream;

2) Call the method to encapsulate each element in the Stream again;

3) Convert stream < stream > to List;

Output results:

=map list=
map list size: 6

The results are in line with expectations.

In addition, I also sorted out the Java 8 knowledge points into small programs, which are often tested in interviews. You can brush questions online in the Java interview library applet.

If all the elements in the List are integers:

private static List<String> NUMBERS_LIST = Arrays.asList("22", "19", "89", "90");

Then you can directly use the built-in mapToXxx method. Here, mapToLong is used to demonstrate:

 * mapToLong transformation
 * @author: Stack length
 * @from: Official account Java technology stack
private static void mapToLong() {
    System.out.println("=====map to long list=====");
    List<Long> longList =;
    System.out.println("map to long list size: " + longList.size());

1) First convert the List to Stream;

2) Call the Stream.mapToLong method to convert the stream to LongStream type;

3) Call the LongStream.boxed method to collect as stream < long > type;

4) Convert stream < long > to List;

Output results:

=map to long list=
map to long list size: 4

Of course, this can also be achieved using map, but maptoxx can be used to convert the original Stream to XxxStream:

XxxStream can have more functions based on integer type, such as quickly summarizing elements (sum), finding the maximum number (max), the minimum number (min), etc. if element calculation is involved, maptoxx will be more popular.

As shown in the source code:

<R> Stream<R> map(Function<? super T, ? extends R> mapper);
LongStream mapToLong(ToLongFunction<? super T> mapper);

The return types of map and mapToXxx are different.

All the complete sample source code of this article has been uploaded:


The function of flatMap method:

flat means tiling. flatMap means that after each element in the convection is tiled, multiple flows are formed together

For example, there are now three string arrays:

String[] arr1 = {"https://", "www", ".", "javastack", ".", "cn"};
String[] arr2 = {"official account", ":", "Java Technology stack"};
String[] arr3 = {"author", ":", "Stack length"};

Now convert directly to Stream:

System.out.println("=====arrays list=====");
List<String[]> list = Stream.of(arr1, arr2, arr3).collect(Collectors.toList());
System.out.println("\narrays list size: " + list.size());

Result output:

=arrays list=
arrays list size: 3

Yes, it's three array elements.

Let's look at the effect of using flatMap method:

System.out.println("=====flatmap list=====");
List<String> mapList =;
System.out.println("\nflatmap list size: " + mapList.size());

Result output:

=flatmap list= official account : Java technology stack Author: stack length
flatmap list size: 12

The element size becomes 12. All the elements in the three array streams are tiled into one stream, and then there are a total of 12 elements in the stream.

The array type I use here can also be multiple list < string > types, and its bottom layer is also an array, as long as it can convert elements into streams.


map refers to the conversion of convection elements. flatMap refers to the merging of elements (arrays) in the convection after tiling, that is, each element in the convection is converted into a Stream stream after tiling.

Let's look at the source code of the following two methods:

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

The parameters are different. Each element before and after the map is of type R, and each element before and after the flatMap has changed from the original R type to the Stream type.

To sum up:

map is suitable for simple conversion of each element, and flatMap is suitable for tiling and merging array streams. The application scenarios of the two methods are different.

So, have you failed? Use it in the project quickly, improve your hard strength and let your colleagues look at you with new eyes! Again, the new knowledge points for Java 8 will not be used. We can pay attention to the official account: Java technology stack, back to back: Java, Java 8+ series, I have written a bunch.

All the complete sample source code of this article has been uploaded:

Welcome to Star. The following Java examples will be provided here!

Well, today's sharing is here. The stack will share more interesting Java technology and latest technology information. We will pay attention to the Java push for the official account. I will also organize the main Java interview questions and reference answers. I will reply to the key words in the official account.

Finally, I feel that if my article is useful to you, use your small hand to read and forward it. It is not easy to be original. The stack leader needs your encouragement.

Copyright notice: This article is the public number "Java technology stack" original, original is not easy, reprint, quote the content of this article please indicate the source, all the plagiarism official account + complaint, and retain the right to pursue its legal responsibility.

Recent hot article recommendations:

1.1000 + Java interview questions and answers (2021 latest version)

2.Stop playing if/ else on the full screen. Try the strategy mode. It's really fragrant!!

3.what the fuck! What is the new syntax of xx ≠ null in Java?

4.Spring Boot 2.6 was officially released, a wave of new features..

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don't forget to like + forward!

Posted by kday on Wed, 24 Nov 2021 04:51:41 -0800