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:

Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Tiêu chuẩn coding trong Java (Coding Standards)
Hướng dẫn sử dụng String Format trong Java
Java Program to find the maximum subarray sum using Binary Search approach
Spring AMQP in Reactive Applications
Guide to ThreadLocalRandom in Java
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Java Program to Implement Hash Tables Chaining with Doubly Linked Lists
Java Program to Implement Bresenham Line Algorithm
How to Change the Default Port in Spring Boot
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Java Program to Compare Binary and Sequential Search
Bootstrapping Hibernate 5 with Spring
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Functional Interface trong Java 8
Java Program to Implement Doubly Linked List
Finding Max/Min of a List or Collection
Java Program to Generate Random Numbers Using Multiply with Carry Method
Kết hợp Java Reflection và Java Annotations
Java Program to Implement the Vigenere Cypher
Introduction to Spring Cloud OpenFeign
Introduction to Using Thymeleaf in Spring
Java – String to Reader
Java Program to Solve any Linear Equations
Java Program to Find Inverse of a Matrix
Java Program to Check whether Directed Graph is Connected using DFS
Check if there is mail waiting
Java – Reader to InputStream
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
Using a List of Values in a JdbcTemplate IN Clause
Generating Random Dates in Java
Debug a JavaMail Program