Java Stream flatMapToLong() with examples

 332 total views,  2 views today

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

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

Before learning flatMapToLong() let us understand flattening?

What is flattening?

Flattening helps in converting a 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 flatMapToLong()

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

It transforms the data as well as flatten the collection.

Method description

LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)

As per official documentation,

Returns an LongStream 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 flatMapToLong() is an intermediate operation it will have two characteristics.

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

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

flatMapToLong() example

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

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

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

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

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

		    .flatMapToLong(item -> 





Java Stream flatMapToLong() operation is mainly used for transforming and flattening a collection.flatMapToLongt() will always create a new LongStream 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!.