首页 > 解决方案 > 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?

标签: javahashmap

解决方案


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...


推荐阅读