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

Java如何将Map值作为键关联其他Map值生成新Map列表?

实现方案

首先修正原代码的两处语法错误:

  • three实例化时HasMap拼写错误,应为HashMap
  • 原有遍历空four集合的逻辑不符合需求,改为直接构造两个目标Map存入集合即可

完整实现代码

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapProcessDemo {
    public static void main(String[] args) {
        Map<String, String> one = new HashMap<>();
        one.put("Medicine","Doctor");
        one.put("Engineering","Engineer");

        Map<String, String> two =new HashMap<>();
        two.put("Medicine","MBBS");
        two.put("Engineering","Software Engineer");

        Map<String, String> three = new HashMap<>();
        three.put("Medicine","Ortho");
        three.put("Engineering","Aerospace Engineer");

        List<Map<String, String>> four= new ArrayList<>();
        Map<String, String> mapForTwo = new HashMap<>();
        Map<String, String> mapForThree = new HashMap<>();

        // 以one的键作为公共匹配维度,遍历生成目标Map
        for (String commonKey : one.keySet()) {
            String newKey = one.get(commonKey);
            mapForTwo.put(newKey, two.get(commonKey));
            mapForThree.put(newKey, three.get(commonKey));
        }

        four.add(mapForTwo);
        four.add(mapForThree);

        // 打印验证结果
        four.forEach(System.out::println);
    }
}

运行输出

{Doctor=MBBS, Engineer=Software Engineer}
{Doctor=Ortho, Engineer=Aerospace Engineer}

注:你给出的预期输出中第二个key写为Engineering属于笔误,按照one的映射规则,Engineering对应的value是Engineer,上述输出符合需求的映射逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:54:04