0

how to traverse in guava table ? I have such a table

0 --> 1 [16, 48, 32] 
0 --> 2 [38, 19, 17, 28, 48] 
0 --> 3 [37, 41, 31, 16] 

1 --> 0 [19, 24, 37, 11, 14, 32] 
1 --> 2 [45, 15, 37, 22] 
1 --> 3 [22, 31, 16, 28, 33, 37] 

2 --> 0 [15, 23, 49, 35] 
2 --> 1 [48, 35, 21, 39] 
2 --> 3 [24, 46, 22, 24, 41] 

3 --> 0 [48, 11, 17, 25, 29] 
3 --> 1 [34, 49, 19, 28] 
3 --> 2 [49, 11, 47, 31] 

I want to find sum of a row value and a column value and difference of them. For example;

[(0-->1)+(0-->2)+(0-->3)]-[(1-->0)+(2-->0)+(3-->0)]

Buğra
  • 33
  • 5

1 Answers1

0

If you are using Guava's Table data structure then you can easily get a collection of row/column values by rowKey/columnKey. e.g.:

Random random = new Random();
ImmutableTable.Builder<Integer, Integer, Integer> builder = ImmutableTable.builder();
for (int rowKey = 0; rowKey < 4; rowKey++) {
    for (int columnKey = 0; columnKey < 4; columnKey++) {
        builder = builder.put(rowKey, columnKey, random.nextInt(100));
    }
}
ImmutableTable<Integer, Integer, Integer> table = builder.build();

int rowSum = table.row(0).values().stream().mapToInt(Integer::intValue).sum();
int columnSum = table.column(0).values().stream().mapToInt(Integer::intValue).sum();
int difference = rowSum - columnSum;

If you cannot use Java 8's Stream API then to sum a row/column you would still use table.row(rowKey).values()/table.column(columnKey).values() to get the values in the desired row/column and then write your own method to sum those values.

mfulton26
  • 29,956
  • 6
  • 64
  • 88