简体   繁体   中英

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

Assuming Pair is as follows.

public class Pair<T, U> {

    public final T first;
    public final U second;

    public static <T, U> Pair<T, U> of(T first, U second) {
        return new Pair<>(first, second);
    }

    public Pair(T first, U second) {
        this.first = first;
        this.second = second;
    }

}

Then how about:

    String wordToFilterFor = "abc";
    Integer integerSum = wordTopic.entrySet()
            .stream()
            .filter(entry -> entry.getKey().first.equals(wordToFilterFor))
            .map(e -> e.getValue())
            .mapToInt(Integer::intValue).sum();

Basically start the Stream with the entrySet, so that you have access to the Pair kay. Then filter for the Pair's word.

You can create a function as such:

int getSummationOfValuesByKey(Map<Pair<String,Integer>, Integer> map, String key) {
          return map.entrySet()
                    .stream()
                    .filter(e -> e.getKey().getKey().equals(key))
                    .mapToInt(Map.Entry::getValue)
                    .sum();
}

which given a map and a key will return the summation of the values where the Pair's key is equal to the provided key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM