Home >Java >javaTutorial >How Can I Efficiently Flatten a Nested List in Java 8?

How Can I Efficiently Flatten a Nested List in Java 8?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 02:58:09388browse

How Can I Efficiently Flatten a Nested List in Java 8?

Flattening Nested Lists in Java 8

Given a List> with potentially nested lists, you may encounter the need to merge it into a single List that maintains the original iteration order. To accomplish this efficiently in Java 8, consider the following approach:

Using flatMap and Collectors

Leverage the power of Java 8's flatMap operation to flatten the nested lists into a single stream. The process involves converting each internal list into a stream using List::stream and then flattening them using flatMap.

To preserve the original order of elements, you can collect the result using Collectors.toList(), which creates a new list from the flattened stream, ensuring that the order of elements is maintained.

Code Example:

List<List<Object>> list = ...; // Initialize your nested list

List<Object> flat = list.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());

This code first converts the nested lists into streams, flattens them into a single stream using flatMap, and finally collects the result into a new List called flat, which contains all the objects from the original nested list in the same iteration order.

The above is the detailed content of How Can I Efficiently Flatten a Nested List in Java 8?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn