Just Learn Code

Streamline Your Java Code with flatMap(): Flattening Filtering and Operating on Primitive Types

Introduction to flatMap() in Java

Programming in Java involves performing numerous operations on arrays, lists, maps, and other data structures. One of the most useful operations is the stream() method for creating streams of elements or objects.

The stream() method comes with several functional interfaces that enable you to perform operations on a stream of objects. flatMap() is one of the most commonly used methods in Java for processing streams.

In this article, we will explore what flatMap() is, its relation to map() operation, and how to use it to flatten a list of lists.

Definition of flatMap()

flatMap() is a terminal operation that enables you to flatten a stream of objects into a single stream. The flatMap() method takes each element of a stream of objects, processes it, and returns a new stream that is concatenated with the previous ones.

The resulting stream is then concatenated with the stream elements produced by other stream elements. In other words, flatMap() method takes a stream of elements as an input and returns a stream of arrays, lists, or sets as an output.

Relation to map() operation

The map() operation in Java is used to transform each element of a stream into a new element of a stream. map() operation is known as a ‘lazy operation’ because it returns a new stream instance without executing any code.

On the other hand, flatMap() operation is known as an ‘eager operation’ because it returns a new stream instance after executing code. The flatMap() operation does not only transform each element of a stream but also flattens a collection of streams into a single stream.

The primary difference between flatMap() and map() lies in their return types. While map() returns a stream of transformed objects, flatMap() returns a stream of objects created by the streams’ elements.

Flattening in Java

Want to turn a list of lists into a single-level list?

Flattening in Java refers to the process of converting a collection of lists into a single list.

Flattening a list involves converting a multi-level list into a single-level list by concatenating the elements of each nested list into a single list. Java’s flatMap() method comes in handy when creating a single-level list from a List of Lists.

How to Use flatMap() Method in Java

Creating a stream of objects from a List

Before using flatMap() to transform a stream, you must first create a stream of objects from which to process. Using the stream() method in combination with a List is the most common way to create a stream of objects.

For instance:

List numbers = Arrays.asList(1, 2, 3, 4, 5);

Stream integerStream = numbers.stream();

Using flatMap() to flatten a list of lists

Assume that you have a list of Programmers, each containing a list of programming languages they know. You need to create a list of all programming languages without nesting, i.e., a single-level list.

The flatMap() method comes in handy for this:

public class Programmer {

List skills = new ArrayList();

//Other characteristics of the programmer class, constructors


List programmers = new ArrayList<>();

Programmer p1 = new Programmer();



Programmer p2 = new Programmer();



Programmer p3 = new Programmer();






List programmingLanguages = programmers.stream().flatMap(p -> p.skills.stream()).collect(Collectors.toList());


In the code above, we create a List of programmers and add several Programmers each with a List of Programming languages. We then create a stream of these programmers and map them to their skills lists, which we output on the console using System.out::println.


The flatMap() method is an essential Java tool for flattening a stream and transforming it into a single stream. FlatMap() facilitates the process of flattening Lists of Lists in Java, making it possible to get rid of layers of nesting and create a simple, single-level list.

With flatMap(), Java programmers can improve their code’s readability and efficiency. It is a must-have tool in every programmer’s arsenal.

Removing Duplicates with flatMap() in Java

One of the common issues that programmers face when working with flattened lists is the presence of duplicates. Duplicates can make the data difficult to interpret and lead to errors in the code.

Java’s flatMap() method allows you to avoid duplicates in a flattened list. To eliminate duplicates in a list, we can use the distinct() operation.

Eliminating duplicates in a flattened list

Java has a built-in distinct() operation that eliminates the duplicates in a stream. distinct() operation ensures that the output stream contains no duplicates.

We can use the distinct() operation in combination with flatMap() to eliminate duplicates in a flattened list. Here’s an example:

List list1 = Arrays.asList(1, 2, 3, 4, 5);

List list2 = Arrays.asList(6, 7, 8, 9, 10);

List list3 = Arrays.asList(1, 2, 3, 4, 5);

List list4 = Arrays.asList(11, 12, 13, 14, 15);

List> listOfLists = new ArrayList<>();





List flattenedList = listOfLists.stream().flatMap(Collection::stream).distinct().collect(Collectors.toList());


In the code above, we create four lists, each containing unique elements.

We then create a List of Lists that contains all four lists, including a duplicate of the first List. To eliminate duplicates, we first create a stream of the List of Lists using the stream() method and then apply the flatMap() method, which flattens all the lists.

Finally, we apply the distinct() operation to remove duplicates. The resulting List contains all unique elements from all four original Lists.

Filtering with flatMap() in Java

Java’s flatMap() method is also useful for filtering lists, enabling developers to transform and manipulate data in their applications. Java’s filter() function is the perfect complement to flatMap() for filtering out specific elements in a List.

The filter() function applies a predicate to each element in a stream, resulting in a new stream that includes only the elements that satisfy the condition.

Using filter() to get all elements except for a specific one

In Java, filtering a stream of objects is achieved through the filter() method, which returns a new stream containing elements that meet a condition specified in a predicate. In combination with flatMap(), filter() can be useful in creating a new List that contains all the elements of a flattened List except for a specific one.

Let’s look at an example:

List> listOfLists = new ArrayList<>();

List list1 = Arrays.asList(1, 2, 3);

List list2 = Arrays.asList(4, 5, 6);

List list3 = Arrays.asList(7, 8, 9);




Integer unwantedNumber = 5;

List filteredList = listOfLists.stream()


.filter(number -> !number.equals(unwantedNumber))



In the code above, we created a List of Lists with three elements, each containing three integers. We want to create a new List containing all integers in the original list of lists except for the number 5.

In the example, we use flatMap() to flatten all the lists into a single List, then apply the filter() method to exclude the unwanted number. Finally, we collect the result into a new List and output the filtered List to the console.


Java’s flatMap() method is an important tool in modern Java development, allowing you to transform and manipulate data more effectively. FlatMap() makes it easier to flatten Lists of Lists in Java, which can help eliminate the complexity of processing nested data.

In combination with the distinct() and filter() operations, you can take stream processing in Java to the next level of productivity and efficiency. Programmers can leverage these features to improve their code and make it more readable, reliable and efficient.

flatMap() with Primitive Types in Java

Java’s flatMap() method works well with object types such as Integer, String, and other non-primitive types. It can also be useful with primitive types, like int, long, float, etc., and in this case, we use the flatMapto{primitive type} method.

This allows you to conduct operations on streams of primitive types as opposed to streams of object types. By leveraging flatMapto{primitive type} method, you can simplify your code and make it faster and more efficient.

Using flatMapto{primitive type} for primitive data types

Java provides specialized versions of the flatMap() method called flatMapto{primitive type}. These methods apply to streams of primitive types: IntStream, LongStream, DoubleStream, and others.

For instance, let’s say we have a List of arrays that holds a variety of integer arrays:

List numbersList = Arrays.asList(

new int[]{1, 2, 3},

new int[]{4, 5},

new int[]{6, 7, 8},

new int[]{9}


To flatten out the list above using flatMap() with object types, we might write the following code:

List flattenedList = numbersList




This works fine, but if you try using flatMap() with a primitive type like int, you’ll get an error. Instead, we can use the flatMapto{primitive type} method as shown below:

int[] flattenedArray = numbersList




In the code above, flatMapToInt() streams the integer arrays and concatenates them into a single IntStream, which is returned as an output.

The toArray() method then converts the IntStream into an array of integers. This technique is not only faster and more efficient than using the object flatMap() method but also more convenient to use.

We can also use flatMaptoLong() or flatMaptoDouble() methods to operate on long and double type data accordingly.


By leveraging the flatMapto{primitive type} method, Java developers can perform complex operations with much greater efficiency and speed. Working with primitive types using flatMapto{primitive type} method not only makes your code more readable but can also ensure better performance.

FlatMapto{primitive type} makes it possible to flatten List’s containing primitive arrays, making them easier to work with and manipulate. Java’s flatMap() method continues to be one of the most powerful tools in any Java developer’s toolkit for making their code more concise, readable, and efficient.

In conclusion, Java’s flatMap() method is an essential tool for processing streams of objects and can be used to manipulate and transform data more efficiently. The flatMap() method can be used to flatten nested Lists and eliminate duplicates by leveraging the Java distinct() operation.

Additionally, combining flatMap() with the filter() method allows developers to retrieve elements from a List that satisfy a specific condition. When working with primitive types, flatMapto{primitive type} method offers a faster and more convenient way to manipulate and operate on streams of primitive types.

These powerful tools can drastically improve the readability, performance, and efficiency of your Java code. Leverage flatMap() and its related methods to process streams of objects and primitive types more efficiently, and also to make the code more readable and concise.

Popular Posts