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:

Check if a String is a Palindrome in Java
Serverless Functions with Spring Cloud Function
Java Program to Show the Duality Transformation of Line and Point
Java NIO2 Path API
Using Java Assertions
Shuffling Collections In Java
Adding Parameters to HttpClient Requests
Hướng dẫn Java Design Pattern – Proxy
Java Program to Find the GCD and LCM of two Numbers
Apache Commons Collections Bag
Spring Boot Gradle Plugin
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
JWT – Token-based Authentication trong Jersey 2.x
Java Program to find the maximum subarray sum using Binary Search approach
Spring Cloud AWS – Messaging Support
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Implement AttributeList API
Java Program to Perform Polygon Containment Test
Finding the Differences Between Two Lists in Java
Quick Guide to the Java StringTokenizer
Using Spring ResponseEntity to Manipulate the HTTP Response
Java 9 Stream API Improvements
Guide to Selenium with JUnit / TestNG
Spring Boot Actuator
Spring RestTemplate Request/Response Logging
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Java Program to Describe the Representation of Graph using Incidence List
Function trong Java 8
Guide to Escaping Characters in Java RegExps
Java Program to Implement LinkedHashMap API
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree