在Google Guava中打印HashBasedTable的所有键和值

我使用以下代码创建并填充Guava Table

 Table table = HashBasedTable.create(); table.put("A", "B", 1); table.put("A", "C", 2); table.put("B", "D", 3); 

我想知道如何迭代表并打印每行的键和值? 所以,期望的输出是:

 AB 1 AC 2 BD 3 

我不是番石榴用户所以这可能是矫枉过正(如果它是真的那么会很高兴任何信息)但你可以使用table.rowMap()来获取Map> ,它将代表表中的数据forms{A={B=1, C=2}, B={D=3}} 。 然后迭代这个地图,如:

 Map> map = table.rowMap(); for (String row : map.keySet()) { Map tmp = map.get(row); for (Map.Entry pair : tmp.entrySet()) { System.out.println(row+" "+pair.getKey()+" "+pair.getValue()); } } 

要么

 for (Map.Entry> outer : map.entrySet()) { for (Map.Entry inner : outer.getValue().entrySet()) { System.out.println(outer.getKey()+" "+inner.getKey()+" "+inner.getValue()); } } 

或者甚至更好地使用com.google.common.collect.Table.Cell

 for (Cell cell: table.cellSet()){ System.out.println(cell.getRowKey()+" "+cell.getColumnKey()+" "+cell.getValue()); }