Java Stream flatMapToInt() with examples

 719 total views,  2 views today

Welcome to Java 8 series. In this tutorial, you will learn about java stream flatMapToInt() with examples.

flatMapToInt() is a part of the Stream pipeline and an intermediate operation. It belongs to the Stream interface.

Before learning flatMapToInt() let us understand flattening?

What is flattening?

Flattening helps in converting collection of several list or collections into a single collection. It merges all list of collections to form a single collection.

Flattening =  Collection<Collection <T>> to Collection<T>


[[a,b,c],[d,e,f],[g,h],[i,j,k,l,m] = [a,b,c,d,e,f,g,h,i,j,k,l,m]
It flatten out several lists of data into single list.

What is flatMapToInt()

flatMapToInt() flattens the stream of collections to form a single IntStream.It uses map() + flatten() operations on the input stream.

It transforms the data as well as flatten the collection.

Method description

IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)

As per official documentation,

Returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

Since flatMapToInt() is an intermediate operation it will have two characteristics.

  1. flatMapToInt() is lazy loading operation. This means data will only be mapped and flattened when a terminal operation is invoked on the stream.
  2. flatMapToInt() operation on a stream will always create a new IntStream output.

Let us now see a few examples of Java 8 stream flatMapToInt()

flatMapToInt() example

import java.util.ArrayList;
import java.util.List;

public class StaticReference {
	public static void main(String[] args) {

		List<List<Integer>> list = new ArrayList<List<Integer>>();
		List<Integer> list1 = new ArrayList<>();

		List<Integer> list2 = new ArrayList<>();

		List<Integer> list3 = new ArrayList<>();

		    .flatMapToInt(item ->





Java Stream flatMapToInt() operation is mainly used for transforming and flattening a collection. flatMapToInt() will always create a new IntStream and it is lazily evaluated.

References : Official documentation

Thanks for reading. Please a comment and give us a thumbs up! 

Tags :

About the Author


Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us ( and give a thumbs up :) Feel free to contact me for any queries!.