Print all keys and value for HashBasedTable in Google Guava

后端 未结 2 1793
独厮守ぢ
独厮守ぢ 2021-01-07 21:51

I create and populate a Guava Table using the following code:

Table table = HashBasedTable.create();
table.put(\"A\", \"B\", 1         


        
相关标签:
2条回答
  • 2021-01-07 21:53

    you can use :

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

    and the output will be

    [{A={B=1, C=2}, B={D=3}}]
    
    0 讨论(0)
  • 2021-01-07 22:20

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

    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

    for (Cell<String, String, Integer> cell: table.cellSet()){
        System.out.println(cell.getRowKey()+" "+cell.getColumnKey()+" "+cell.getValue());
    }
    
    0 讨论(0)
提交回复
热议问题