java - how to get summation of pair(key) values in a map in java?
问题描述
I have a map which represents a matrix of string-int that maps to a value:
static Map<Pair<String,Integer>, Integer> wordTopic = new HashMap<>();
I want to get the summation of values that has a specific string (a part of the pair) not the whole pair Pair<String,Integer>
AKA the summation of one row.
Example: the matrix
string/int 1 2
value1 13 26
value2 11 22
i want the summation of row values of string "value1" ..output should be =39
I have found this: Integer integerSum = wordTopic.values().stream().mapToInt(Integer::intValue).sum();
but this will get me the summation of the values of the whole key AKA the whole matrix ,i want the summation of the row only..any hints?
解决方案
I presume this:
Input:
a-1 = 100
a-2 = 200
b-4 = 400
b-8 = 800
Output:
a = 300
b = 1200
Using map.entries() will probably help deal with the row more easily.
You seem to want to group by strings first, so a .group() lambda examining the Map.Entry.getKey().getValue0() would make a map of <String, List<Map.Entry>>
and for each one of those, you would do the desired .map & .sum, etc (left as homework...)
You can probably tell that a good old for loop with another hashmap is going to be more readable...
推荐阅读
- itext - 如何在 Itext7 中使用自定义颜色和自定义字体
- android - 如何使用 AWS C++ SDK 为 Android 构建 Qt 应用程序?
- netty - Netty SctpMultiChannel
- android - IONIC 3 android应用程序启动延迟
- authentication - Wireshark - 从连接的 AP 捕获 AUTH&ASSOC 数据包
- ios - 裁剪 UIImage 没有产生预期的作物 - 迅速?
- aws-glue - AWS Glue 作业 python 脚本
- java - 当用户单击卡片视图时,如何从 Firebase 实时数据库中删除卡片视图上显示的特定记录。
- python - 如何在不使用函数的情况下在 python 中打印名称的反面?
- android - 圆角 ExpandableListView