在Google Guava中打印HashBasedTable的所有键和值 [英] Print all keys and value for HashBasedTable in Google Guava
问题描述
我创建并填充番石榴表
使用以下代码:
I create and populate a Guava Table
using the following code:
Table<String, String, Integer> table = HashBasedTable.create();
table.put("A", "B", 1);
table.put("A", "C", 2);
table.put("B", "D", 3);
我想知道如何迭代表并打印每行的键和值?所以,期望的输出是:
I wonder how to iterate over table and print out both keys and value for each row? So, the desired output is:
A B 1
A C 2
B D 3
推荐答案
我不是番石榴用户所以这可能是矫枉过正(如果是真的那么将会很高兴任何信息)但您可以使用 table.rowMap()
来获取 Map< String,Map< String,Integer>>
,它将以表格 {A = {B = 1,C = 2},B = {D = 3}}
表示表格中的数据。然后只需迭代这个地图就像:
Im not Guava user so this may be overkill (if it is true then will be glad for any info) but you can use table.rowMap()
to get Map<String, Map<String, Integer>>
which will represents data in table in form {A={B=1, C=2}, B={D=3}}
. Then just iterate over this map like:
Map<String, Map<String, Integer>> map = table.rowMap();
for (String row : map.keySet()) {
Map<String, Integer> tmp = map.get(row);
for (Map.Entry<String, Integer> pair : tmp.entrySet()) {
System.out.println(row+" "+pair.getKey()+" "+pair.getValue());
}
}
或
for (Map.Entry<String, Map<String,Integer>> outer : map.entrySet()) {
for (Map.Entry<String, Integer> inner : outer.getValue().entrySet()) {
System.out.println(outer.getKey()+" "+inner.getKey()+" "+inner.getValue());
}
}
甚至更好地使用 com .google.common.collect.Table.Cell
for (Cell<String, String, Integer> cell: table.cellSet()){
System.out.println(cell.getRowKey()+" "+cell.getColumnKey()+" "+cell.getValue());
}
这篇关于在Google Guava中打印HashBasedTable的所有键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!