java - Java:合并两个 com.google.common.collect.Table
问题描述
我有两个Table
像:
Table<Long,String,Integer> tableOne
Table<Long,String,Integer> tableTwo
如何合并两个值相加的表(如果需要)?
所以结果我会得到一个
Table<Long,String,Integer> sumTable
例如,我有以下值:
在表一中:
1L Fruits 20
2L Fruits 30
2L Vegetables 15
3L Vegetables 10
在表二
2L Fruits 10
2L Vegetables 40
3L Fruits 15
4L Vegetables 35
所以总和是:
1L Fruits 20
2L Fruits 30 + 10 = 40
2L Vegetables 15 + 40 = 55
3L Vegetables 10
3L Fruits 15
4L Vegetables 35
我会很欣赏 Java8 流式解决方案,但也可以接受经典的。
解决方案
您可以使用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);
输出
(1,Fruits)=20
(2,Fruits)=40
(2,Vegetables)=55
(3,Vegetables)=10
(3,Fruits)=15
(4,Vegetables)=35
推荐阅读
- docker - Jenkinsfile 中的 Dockerfile 构建不一致(连接失败错误)
- html - SyntaxError: Unexpected token / while compile EJS
- php - 使用正则表达式从 url 中查找 Fb Post id
- python - 数据框编辑
- pyqt - PyQT5 - setUnifiedTitleAndToolBarOnMac
- python - 无法将输入数组从形状 (2,2) 广播到形状 (2)
- wordpress - 结帐期间创建帐户 Woocommerce
- ubuntu-18.04 - Dovecot 不在 maildir 中定位消息,如何解释调试日志?
- excel - .Find 后存储范围值
- c - 带有 PTRACE_O_EXITKILL 的 PTRACE_SETOPTIONS 不起作用:参数无效