Java: Merge two com.google.common.collect.Table

1k Views Asked by At

I have two Tables like:

Table<Long,String,Integer> tableOne
Table<Long,String,Integer> tableTwo

How can I merge the two tables where the values are summed(if needed)?

So as a result I would get a

Table<Long,String,Integer> sumTable 

For example I have the following values:

in tableOne:

   1L Fruits     20
   2L Fruits     30
   2L Vegetables 15
   3L Vegetables 10

in tableTwo

   2L Fruits     10
   2L Vegetables 40
   3L Fruits     15
   4L Vegetables 35

so the sum would be:

   1L Fruits     20
   2L Fruits     30 + 10 = 40
   2L Vegetables 15 + 40 = 55
   3L Vegetables 10
   3L Fruits     15
   4L Vegetables 35

I would appreciate a Java8 stream-way solution, but a classical would be also acceptable.

1

There are 1 best solutions below

1
Dani Mesejo On BEST ANSWER

You could use Tables.toTable:

Table<Long, String, Integer> tableOne = HashBasedTable.create();
tableOne.put(1L, "Fruits", 20);
tableOne.put(2L, "Fruits", 30);
tableOne.put(2L, "Vegetables", 15);
tableOne.put(3L, "Vegetables", 10);

Table<Long, String, Integer> tableTwo = HashBasedTable.create();
tableTwo.put(2L, "Fruits", 10);
tableTwo.put(2L, "Vegetables", 40);
tableTwo.put(3L, "Fruits", 15);
tableTwo.put(4L, "Vegetables", 35);


HashBasedTable<Long, String, Integer> sumTable = Stream.concat(tableOne.cellSet().stream(), tableTwo.cellSet().stream())
        .collect(Tables.toTable(Table.Cell::getRowKey,
                Table.Cell::getColumnKey,
                Table.Cell::getValue,
                Integer::sum, HashBasedTable::create));

sumTable.cellSet().forEach(System.out::println);

Output

(1,Fruits)=20
(2,Fruits)=40
(2,Vegetables)=55
(3,Vegetables)=10
(3,Fruits)=15
(4,Vegetables)=35