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:

The Spring @Controller and @RestController Annotations
Spring Boot - Thymeleaf
Java Program to Implement Shoelace Algorithm
Java Program to Implement JobStateReasons API
Java Program to Find kth Largest Element in a Sequence
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Java Program to Implement VList
Assert an Exception is Thrown in JUnit 4 and 5
Intro to Inversion of Control and Dependency Injection with Spring
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Java Program to Show the Duality Transformation of Line and Point
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Convert Time to Milliseconds in Java
XML-Based Injection in Spring
REST Web service: Upload và Download file với Jersey 2.x
Java Program to Implement Sieve Of Eratosthenes
Java String Conversions
How to Set TLS Version in Apache HttpClient
Java Program to Implement TreeMap API
Spring Data MongoDB Transactions
Intersection of Two Lists in Java
Java Program to Implement Bresenham Line Algorithm
Lớp Arrarys trong Java (Arrays Utility Class)
Spring @RequestParam Annotation
Converting Between a List and a Set in Java
Java Program to Decode a Message Encoded Using Playfair Cipher
Inheritance with Jackson
“Stream has already been operated upon or closed” Exception in Java
An Example of Load Balancing with Zuul and Eureka
Prevent Brute Force Authentication Attempts with Spring Security
Spring REST API with Protocol Buffers
How to Remove the Last Character of a String?