如何遍历嵌套的List<List>结构

在实际开发中,我们经常会遇到嵌套的List<List>结构,这种情况下如何高效地进行遍历是一个常见的问题。在本文中,我们将探讨如何使用Java 8的Stream API来遍历嵌套的List<List>结构,并解决一个实际问题。

问题描述

假设我们有一个嵌套的List<List>结构,其中包含了多个学生及其对应的课程列表。我们想要找出所有学生所选的所有课程,并将其打印出来。

List<List<String>> studentsAndCourses = new ArrayList<>();
studentsAndCourses.add(Arrays.asList("Alice", "Math", "English"));
studentsAndCourses.add(Arrays.asList("Bob", "History", "Science"));
studentsAndCourses.add(Arrays.asList("Charlie", "Art", "Music"));

解决方案

我们可以使用Java 8的Stream API来遍历嵌套的List<List>结构。首先我们可以通过flatMap方法将嵌套的List转换为一个扁平的流,然后使用forEach方法来对每个元素进行操作。

studentsAndCourses.stream()
    .flatMap(List::stream)
    .forEach(course -> System.out.println(course));

在上面的代码中,我们首先通过stream方法将List<List>转换为Stream<List>,然后通过flatMap方法将嵌套的List转换为一个扁平的流,最后使用forEach方法将每门课程打印出来。

示例

下面是完整的示例代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<List<String>> studentsAndCourses = new ArrayList<>();
        studentsAndCourses.add(Arrays.asList("Alice", "Math", "English"));
        studentsAndCourses.add(Arrays.asList("Bob", "History", "Science"));
        studentsAndCourses.add(Arrays.asList("Charlie", "Art", "Music"));

        studentsAndCourses.stream()
            .flatMap(List::stream)
            .forEach(course -> System.out.println(course));
    }
}

输出结果为:

Alice
Math
English
Bob
History
Science
Charlie
Art
Music

通过上面的示例代码,我们成功地遍历了嵌套的List<List>结构,并实现了我们的需求。

总结

本文介绍了如何使用Java 8的Stream API来遍历嵌套的List<List>结构,通过flatMap方法将嵌套的List转换为一个扁平的流,从而方便地对数据进行操作。希望本文对你有所帮助,谢谢阅读!