开满天机
您可以使用and合并两个流Stream.concat()并将它们分组:Collectors.groupingBy()Collectors.mapping()Map<String, String> first = Map.of("1", "a", "2", "a");Map<String, String> second = Map.of("1", "android", "2", "ios");Map<String, List<String>> result = Stream.concat(first.entrySet().stream(), second.entrySet().stream()) .collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList())));System.out.println(result);将输出:{1=[a, android], 2=[a, ios]}
冉冉说
这是得出结果的一种方法:输入数据:// The first list of dataList<Map<String, String>> list1 = new ArrayList<>();list1.add(getMapData("1", "a"));list1.add(getMapData("2", "a"));list1.add(getMapData("3", "b"));list1.add(getMapData("4", "e"));list1.add(getMapData("5", "e"));list1.add(getMapData("999", "x"));System.out.println(list1);资料一:[{1=a}, {2=a}, {3=b}, {4=e}, {5=e}, {999=x}]// The second list of dataList<Map<String, String>> list2 = new ArrayList<>();list2.add(getMapData("1", "android"));list2.add(getMapData("2", "ios"));list2.add(getMapData("3", "android"));list2.add(getMapData("4", "android"));list2.add(getMapData("5", "ios"));list2.add(getMapData("888", "zzzzz"));System.out.println(list2);数据2:[{1=android}, {2=ios}, {3=android}, {4=android}, {5=ios}, {888=zzzzz}]// utility method for creating test dataprivate static Map<String, String> getMapData(String k, String v) { Map<String, String> m = new HashMap<>(); m.put(k, v); return m;}结果过程:输出存储到Map<String, List<String>>:Map<String, List<String>> result = new HashMap<>();// process the first listfor (Map<String, String> m : list1) { for (Map.Entry<String, String> entry : m.entrySet()) { List<String> valueList = new ArrayList<>(); valueList.add(entry.getValue()); result.put(entry.getKey(), valueList); }}// process the second list; merge with the firstfor (Map<String, String> m : list2) { for (Map.Entry<String, String> entry : m.entrySet()) { String k = entry.getKey(); List<String> valueList = result.get(k); if (valueList == null) { valueList = new ArrayList<>(); } valueList.add(entry.getValue()); result.put(k, valueList); }}System.out.println(result);结果:{1=[a, android], 2=[a, ios], 3=[b, android], 4=[e, android], 5=[e, ios], 888=[zzzzz], 999=[x]}
aluckdog
您也可以尝试这种方法:Map<String, String> result1 = new HashMap<>();// initialize result1 ...Map<String, String> result2 = new HashMap<>();// initialize result2 ...Map<String, Map<String, String>> mergedResult = new HashMap<>();高达 Java 8result1.forEach((k1, v1) -> mergedResult.put(k1, new HashMap<String, String>() {{ put(v1, result2.get(k1)); }}));Java 9 或更高版本result1.forEach((k1, v1) -> mergedResult.put(k1, Map.of(v1, result2.get(k1))));