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

Java同键Map转换问题:ID-出现次数映射值为null排查

问题分析与修复

你的代码核心错误在于赋值逻辑:
在给新Map idAndCount 添加元素时,你使用了 firstCounter.get(entry.getValue()),但 entry.getValue() 是当前食材的出现次数(Integer类型),而 firstCounter 的键是食材名称(String类型)——用Integer作为键去查询String键的Map,必然返回null,这就是新Map值全为null的原因。

修正后的代码

Map<String, Long> keywordsToIds;
Map<String, Integer> firstCounter;

Map<Long, Integer> idAndCount = new HashMap<>();

for (Map.Entry<String, Integer> entry : firstCounter.entrySet()) {
    if (keywordsToIds.containsKey(entry.getKey())) {
        // 直接使用entry.getValue()获取当前食材的出现次数
        idAndCount.put(keywordsToIds.get(entry.getKey()), entry.getValue());
    }
}

return idAndCount;

补充说明

  • 遍历firstCounter的entry时,entry.getKey()是食材名称,entry.getValue()就是该食材对应的出现次数,直接使用这个值即可,无需再次调用firstCounter.get()。
  • 建议给循环代码加上大括号,避免后续扩展代码时出现缩进逻辑错误。

可选简化方案(Java 8+ 流API)

如果熟悉Java流操作,可以用更简洁的方式实现:

return firstCounter.entrySet().stream()
        .filter(entry -> keywordsToIds.containsKey(entry.getKey()))
        .collect(Collectors.toMap(
                entry -> keywordsToIds.get(entry.getKey()),
                Map.Entry::getValue
        ));

内容的提问来源于stack exchange,提问作者Escanor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:32:17