How to Flatten a Nested List in Java

In this article, we will learn about nested collections in Java and how we can transform them into flat collections using different approaches.

1. What is Flattening?

In programming, flatting a List means merging several nested lists to create a single list. The flattened list consists of all the elements from the nested lists.

List of nested lists: [[4, 5, 2], [1, 34, 23], [12], [10, 11, 15]];

Flattened List: [4, 5, 2, 1, 34, 23, 12, 10, 11, 15];

We use the following nested list in each solution for demo purposes.

List<List<String>> nestedList = List.of(
      List.of("Alexandru", "John"),
      List.of("Emma","Andrew", "Luke"),
      List.of("Oliver"));

2. Using Custom Logic

One of the most basic solutions is to iterate over the nested Lists and add all the elements into a newly declared flat list. We can add all elements in bulk using addAll() function.

List<String> flatList = new ArrayList<>();

nestedList.forEach(flatList::addAll);

If the original List contains single elements as well then we need to put a if-else condition to first check the type of element.

List<String> flatList = new ArrayList<>();

for (Object item : nestedList) {
  if (item instanceof List<?>) {
      flatList.addAll(item)
  } else {
      flatList.add((String) item);
  }
}

3. Using Streams

The Java Streams API provides us with some interesting methods on how to flatten nested linked lists.

3.1. Using flatMap()

We can use the flatMap() function with the mapper function Collection::stream. On executing the stream terminal operation, each element of flatMap() provides a separate stream. In the final phase, the flatMap() method converts all the streams into a new stream.

List<String> flatList = nestedList.stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toList());

3.2. Using reduce()

The reduction is a terminal method aggregating a stream. In reduce() method, we give two arguments to the functions: the first is called identity, the default value of the reduction, and the second is called accumulator, which combines the two values.

In out case, to get the flattened List, we need to iterate over Stream and merge consecutive lists into one for each successive nested List. Note that due to extra instances of ArrayList created at runtime, this method does not give good performance for large nested lists.

List<String> flatList = nestedList.stream()
		.reduce(new ArrayList<>(), (l1, l2) -> {
		    l1.addAll(l2);
		    return l1;
		});

4. Using Eclipse Collection

Another way to flatten a list of lists would be by using the flatCollect() method from Eclipse Collections. Eclipse Collections is a Java Collections framework that has JDK-compatible List, Map, and, Set implementations with a rich API.

Add the latest version of Eclipse Collection in to the application.

<dependency>
    <groupId>org.eclipse.collections</groupId>
    <artifactId>eclipse-collections</artifactId>
    <version>11.1.0</version>
</dependency>

We will use the ListAdapter class that provides a MutableList wrapper around a JDK Collections List interface instance and converts a Java List into an Eclipse Collection MutableList. After that, we will use its flatCollect() method which will flatten a list of lists.

 List<String> flatList = ListAdapter.adapt(nestedList).flatCollect(e -> e);

5. Using Guava

Add the latest version of Guava from the Maven repo.

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

The Iterables.concat() method is a great fit for creating flat lists from nested lists. This method combines multiple iterables into a single iterable.

Iterable<String> iterable = Iterables.concat(nestedList);

List<String> flatList = Lists.newArrayList(iterable);

6. Conclusion

The flattening of a nested list may seem hard at the beginning, but it’s not. It can be easily done using only plain Java logic, streams, or even external collection libraries.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode