杰瑞科技汇

Java如何实现list嵌套list?

在Java中,嵌套List(即ListList)是一种常见的数据结构,用于表示二维或多维数据,以下是实现和使用嵌套List的详细说明:


声明和初始化嵌套List

使用List<List<T>>表示嵌套列表,其中T是内部列表的元素类型。

示例:初始化嵌套List

import java.util.ArrayList;
import java.util.List;
public class NestedListExample {
    public static void main(String[] args) {
        // 方法1:直接初始化
        List<List<Integer>> nestedList = new ArrayList<>();
        // 方法2:使用Arrays.asList(不可变列表)
        List<List<Integer>> immutableNestedList = List.of(
            List.of(1, 2, 3),
            List.of(4, 5, 6)
        );
        // 方法3:动态添加子列表
        List<List<String>> dynamicNestedList = new ArrayList<>();
        dynamicNestedList.add(new ArrayList<>(List.of("A", "B")));
        dynamicNestedList.add(new ArrayList<>(List.of("C", "D")));
    }
}

添加元素到嵌套List

添加子列表

List<List<Integer>> matrix = new ArrayList<>();
matrix.add(new ArrayList<>(List.of(1, 2, 3))); // 添加第一行
matrix.add(new ArrayList<>(List.of(4, 5, 6))); // 添加第二行

修改子列表中的元素

matrix.get(0).set(0, 99); // 修改第一行第一列的值为99

添加新行或新列

matrix.add(new ArrayList<>(List.of(7, 8, 9))); // 添加新行
matrix.get(0).add(10); // 在第一行末尾添加10

遍历嵌套List

使用嵌套循环或Java 8 Stream API遍历。

方法1:嵌套for循环

for (List<Integer> row : matrix) {
    for (Integer num : row) {
        System.out.print(num + " ");
    }
    System.out.println();
}
// 输出:99 2 3 10 
//       4 5 6 
//       7 8 9 

方法2:Stream API

matrix.stream()
    .flatMap(List::stream)
    .forEach(System.out::println);
// 输出所有元素:99, 2, 3, 10, 4, 5, 6, 7, 8, 9

常用操作示例

创建一个3x3的矩阵

List<List<Integer>> matrix = new ArrayList<>();
for (int i = 0; i < 3; i++) {
    List<Integer> row = new ArrayList<>();
    for (int j = 0; j < 3; j++) {
        row.add(i * 3 + j + 1); // 填充1~9
    }
    matrix.add(row);
}

检查元素是否存在

boolean containsElement = matrix.stream()
    .flatMap(List::stream)
    .anyMatch(x -> x == 5); // 检查是否存在5

获取子列表大小

int rows = matrix.size();       // 行数
int cols = matrix.get(0).size(); // 第一行的列数

注意事项

  1. 空指针异常:访问matrix.get(0)前确保matrix不为空。
  2. 不可变列表:使用List.of()创建的嵌套列表不可修改,否则会抛出UnsupportedOperationException
  3. 性能:频繁操作嵌套List时,考虑使用更高效的数据结构(如数组或第三方库)。

完整示例代码

import java.util.ArrayList;
import java.util.List;
public class NestedListDemo {
    public static void main(String[] args) {
        // 初始化
        List<List<String>> students = new ArrayList<>();
        students.add(List.of("Alice", "Bob"));
        students.add(List.of("Charlie", "David"));
        // 添加新学生
        students.get(0).add("Eve");
        // 遍历输出
        for (List<String> classList : students) {
            System.out.println("Class: " + classList);
        }
        // 输出:
        // Class: [Alice, Bob, Eve]
        // Class: [Charlie, David]
    }
}

通过以上方法,你可以灵活地在Java中操作嵌套List,根据需求选择合适的初始化和遍历方式!

分享:
扫描分享到社交APP
上一篇
下一篇