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
相关产品推荐
相关产品推荐

