java如何遍历table
遍历 Java 中的表格数据
在 Java 中,表格数据通常以二维数组、List<List<T>> 或 JTable(Swing 组件)的形式存在。以下是不同场景下的遍历方法:
遍历二维数组
假设有一个二维数组 String[][] table:
String[][] table = {
{"A1", "B1", "C1"},
{"A2", "B2", "C2"}
};
for (String[] row : table) {
for (String cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
遍历 List<List<T>>
对于嵌套列表结构(如 List<List<String>>):
List<List<String>> table = Arrays.asList(
Arrays.asList("A1", "B1", "C1"),
Arrays.asList("A2", "B2", "C2")
);
for (List<String> row : table) {
for (String cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
遍历 Swing 的 JTable
若使用 Swing 的 JTable 组件,需通过模型获取数据:
JTable table = new JTable(...);
for (int row = 0; row < table.getRowCount(); row++) {
for (int col = 0; col < table.getColumnCount(); col++) {
Object value = table.getValueAt(row, col);
System.out.print(value + " ");
}
System.out.println();
}
使用 Java 8 Stream API
对于集合类表格数据,可以用 Stream 简化遍历:

List<List<String>> table = ...;
table.stream().forEach(row -> {
row.stream().forEach(cell -> System.out.print(cell + " "));
System.out.println();
});
注意事项
- 对于大型表格,注意遍历性能,避免嵌套循环中的复杂操作。
- 若需修改表格数据,在
JTable中应通过模型方法(如setValueAt)操作。 - 使用泛型(如
List<List<String>>)能提高类型安全性。






