Flattening Nested Collections in Java

1. Overview

In this quick article, we’ll explore how to flatten a nested collection in Java.

2. Example of a Nested Collection

Suppose we have a list of lists of type String.

List<List<String>> nestedList = asList(
  asList("one:one"), 
  asList("two:one", "two:two", "two:three"), 
  asList("three:one", "three:two", "three:three", "three:four"));

3. Flattening the List With forEach

In order to flatten this nested collection into a list of strings, we can use forEach together with a Java 8 method reference:

public <T> List<T> flattenListOfListsImperatively(
    List<List<T>> nestedList) {
    List<T> ls = new ArrayList<>();
    nestedList.forEach(ls::addAll);
    return ls;
}

And here you can see the method in action:

@Test
public void givenNestedList_thenFlattenImperatively() {
    List<String> ls = flattenListOfListsImperatively(nestedList);
    
    assertNotNull(ls);
    assertTrue(ls.size() == 8);
    assertThat(ls, IsIterableContainingInOrder.contains(
      "one:one",
      "two:one", "two:two", "two:three", "three:one",
      "three:two", "three:three", "three:four"));
}

4. Flattening the List With flatMap

We can also flatten the nested list by utilizing the flatMap method from the Stream API.

This allows us to flatten the nested Stream structure and eventually collect all elements to a particular collection:

public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
    return list.stream()
      .flatMap(Collection::stream)
      .collect(Collectors.toList());    
}

And here’s the logic in action:

@Test
public void givenNestedList_thenFlattenFunctionally() {
    List<String> ls = flattenListOfListsStream(nestedList);
    
    assertNotNull(ls);
    assertTrue(ls.size() == 8);
}

5. Conclusion

A simple forEach or flatMap methods in Java 8, in combination with method references, can be used for flattening nested collections.

You can find the code discussed in this article over on GitHub.

Related posts:

Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Câu lệnh điều khiển vòng lặp trong Java (break, continue)
Using Spring @ResponseStatus to Set HTTP Status Code
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Removing all Nulls from a List in Java
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Java Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Base64 encoding và decoding trong Java 8
JUnit5 Programmatic Extension Registration with @RegisterExtension
String Initialization in Java
Spring Boot - CORS Support
HttpClient 4 – Send Custom Cookie
Getting Started with GraphQL and Spring Boot
Spring Boot Configuration with Jasypt
How to Break from Java Stream forEach
Java NIO2 Path API
Finding Max/Min of a List or Collection
Guide to java.util.concurrent.Locks
Giới thiệu Design Patterns
Giới thiệu về Stream API trong Java 8
How to Add a Single Element to a Stream
An Intro to Spring Cloud Security
Running Spring Boot Applications With Minikube
Java Program to Find Inverse of a Matrix
Feign – Tạo ứng dụng Java RESTful Client
Java Program to Implement Stack
Java Byte Array to InputStream
Java Program to Implement Fermat Primality Test Algorithm
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Java Program to Implement Floyd Cycle Algorithm
Introduction to Spliterator in Java
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach