You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何对Map内Pair键指定字符串对应的值求和?

解决特定字符串对应行的求和问题

嘿,这问题我熟!要从你这个Map<Pair<String,Integer>, Integer>里算出某个字符串对应所有值的总和,其实有两种常用的写法,我给你一步步讲清楚:

方法一:传统循环遍历(适配所有Java版本)

如果还没用到Java 8的Stream,或者更习惯传统写法,用这个就很稳:

import org.apache.commons.lang3.tuple.Pair; // 假设你用的是Apache Commons的Pair
import java.util.HashMap;
import java.util.Map;

public class YourClass {
    static Map<Pair<String, Integer>, Integer> wordTopic = new HashMap<>();

    public static int calculateRowSum(String targetWord) {
        int total = 0;
        // 遍历Map里的每一个条目
        for (Map.Entry<Pair<String, Integer>, Integer> entry : wordTopic.entrySet()) {
            // 取出Pair里的字符串部分
            String currentWord = entry.getKey().getKey();
            // 匹配目标字符串就累加值
            if (targetWord.equals(currentWord)) {
                total += entry.getValue();
            }
        }
        return total;
    }

    // 测试用例
    public static void main(String[] args) {
        // 模拟你的示例数据
        wordTopic.put(Pair.of("value1", 1), 13);
        wordTopic.put(Pair.of("value1", 2), 26);
        wordTopic.put(Pair.of("value2", 1), 5);

        System.out.println(calculateRowSum("value1")); // 输出39,符合预期
    }
}

注意:如果你的Pair是Java 16+自带的java.util.Pair,那要把getKey()改成getFirst(),不同的Pair实现方法名可能有差异,根据你实际用的库调整就行。

方法二:Java 8+ Stream流(简洁优雅)

要是用的Java 8及以上,用Stream写起来更清爽,核心逻辑一行搞定:

import org.apache.commons.lang3.tuple.Pair;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class YourClass {
    static Map<Pair<String, Integer>, Integer> wordTopic = new HashMap<>();

    public static int calculateRowSumWithStream(String targetWord) {
        return wordTopic.entrySet().stream()
                // 过滤出键中字符串匹配目标的条目,用Objects.equals避免空指针
                .filter(entry -> Objects.equals(entry.getKey().getKey(), targetWord))
                // 把条目里的值转成int流
                .mapToInt(Map.Entry::getValue)
                // 直接求和
                .sum();
    }

    // 测试用例
    public static void main(String[] args) {
        wordTopic.put(Pair.of("value1", 1), 13);
        wordTopic.put(Pair.of("value1", 2), 26);
        wordTopic.put(Pair.of("value2", 1), 5);

        System.out.println(calculateRowSumWithStream("value1")); // 同样输出39
    }
}

这里用Objects.equals是为了避免如果targetWord是null时抛出空指针异常,比直接用equals更安全。

两种方法都能实现你要的效果,选哪种看你的项目Java版本和个人习惯就行~

内容的提问来源于stack exchange,提问作者Abdel-Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:22:07