简体   繁体   English

在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

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

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}} . 我不是Guava用户,因此这可能会过大(如果为true,则将很高兴获得任何信息),但您可以使用table.rowMap()获取Map<String, Map<String, Integer>> ,它将表示表中的数据格式为{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());
    }
}

or 要么

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());
    }
}

or even better using com.google.common.collect.Table.Cell 甚至使用com.google.common.collect.Table.Cell更好

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

you can use : 您可以使用 :

System.out.println(Arrays.asList(table));

and the output will be 和输出将是

[{A={B=1, C=2}, B={D=3}}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM