java 如何将List〈Map〈String,String>>转换为Map〈String,List< String>>

sq1bmfud  于 2023-04-10  发布在  Java
关注(0)|答案(2)|浏览(312)

我有MapList<Map<String,String>>的列表,并希望转换为Map<String, List String>>
下面是示例代码

List<Map<String,String>> recordListMap = new ArrayList<>();

Map<String,String> recordMap_1 = new HashMap<>();
recordMap_1.put("inputA", "ValueA_1");
recordMap_1.put("inputB", "ValueB_1");
recordListMap.add(recordMap_1);

Map<String,String> recordMap_2 = new HashMap<>();
recordMap_2.put("inputA", "ValueA_2");
recordMap_2.put("inputB", "ValueB_2");
recordListMap.add(recordMap_2);

我尝试了下面的方法,但没有得到所需的结果:

Map<String, List<String>> myMaps = new HashMap<>();
for (Map<String, String> recordMap : recordListMap) {
    for (Map.Entry<String, String> map : recordMap.entrySet()) {
        myMaps.put(map.getKey(), List.of(map.getValue()));
    }
}
OutPut: {inputB=[ValueB_2], inputA=[ValueA_2]}

预期结果:

{inputB=[ValueB_1, ValueB_2], inputA=[ValueA_1, ValueA_2]}
juud5qan

juud5qan1#

像这样试试。

  • computeIfAbsent将添加列表作为键的值,如果键不存在。
  • 返回new or existing列表,以便现在可以将对象添加到该列表。
Map<String, List<String>> myMaps = new HashMap<>();
for (Map<String, String> map : recordListMap) {
    for (Entry<String, String> e : map.entrySet()) {
        myMaps.computeIfAbsent(e.getKey(), v -> new ArrayList<>())
                .add(e.getValue());
    }
}
myMaps.entrySet().forEach(System.out::println);

另一种选择是使用流。

  • 流式传输Map列表。
  • 然后流式传输每个map的entrySet,将其展平为单个条目流。
  • 然后按键分组并将值放入列表中。
Map<String, List<String>> myMaps2 = recordListMap.stream()
        .flatMap(map -> map.entrySet().stream())
        .collect(Collectors.groupingBy(Entry::getKey, Collectors
                .mapping(Entry::getValue, Collectors.toList())));

两者都将包含

inputB=[ValueB_1, ValueB_2]
inputA=[ValueA_1, ValueA_2]

查看Map.computeIfAbsent

yyhrrdl8

yyhrrdl82#

请参见Map#compute部分
Map#compute
Map#computeIfPresent
Map#computeIfAbsent
假设您不想使用Multimap,那么类似的东西应该可以解决这个问题。

List<Map<String, String>> list = new ArrayList<>();
    Map<String, List<String>> goal = new HashMap<>();

    for (Map<String, String> map : list) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            goal.compute(entry.getKey(), (k,v)->{
                List<String> l = v == null ? new ArrayList<>() : v;
                l.add(entry.getValue());
                return l;
            });
        }
    }

相关问题