You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何遍历com.google.common.collect.Table类型的表数据

Guava Table 基础遍历实现方法

核心通过Guava Table提供的cellSet()方法实现,该方法会返回表中所有有效单元格的Set集合,每个单元格对应Table.Cell实例,可直接获取行键、列键、值三个属性,完全匹配你的遍历需求。

增强for循环实现(原生foreach风格)

这是最直观、兼容性最好的写法:

import com.google.common.collect.Table;

// 调用预定义函数获取Table实例
Table<ObjType, ObjType, Set<String>> objTable = getPredefinedTableData();

// 遍历所有单元格
for (Table.Cell<ObjType, ObjType, Set<String>> cell : objTable.cellSet()) {
    // 分别获取行对象、列对象、对应的值集合
    ObjType x = cell.getRowKey();
    ObjType y = cell.getColumnKey();
    Set<String> value = cell.getValue();
    
    // 按要求格式输出,可根据ObjType的属性调整输出内容
    System.out.printf("对于ObjType %s和ObjType %s,对应的值为[[%s]]%n", x, y, value);
}

Java 8+ Lambda 简化实现(可选)

如果使用Java 8及以上版本,可以用更简洁的写法:

objTable.cellSet().forEach(cell -> {
    ObjType x = cell.getRowKey();
    ObjType y = cell.getColumnKey();
    Set<String> value = cell.getValue();
    System.out.printf("对于ObjType %s和ObjType %s,对应的值为[[%s]]%n", x, y, value);
});

注意事项

  • 如果需要调整Set的输出格式,比如用逗号拼接所有字符串,可以把输出语句中的value替换为String.join(",", value)
  • 如果自定义类ObjType没有重写toString()方法,直接输出x/y会显示类名+哈希值,你可以根据需求替换为x.getXXX()调用具体属性输出
  • cellSet()默认不会返回值为null的单元格,符合Guava Table的常规行为

内容的提问来源于stack exchange,提问作者user16099288

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:45:10