Search code examples
javacollectionsjava-stream

how to convert List<Map<String, String>> to Map<String, List<String>>


I have list of map List<Map<String,String>> and want to convert into Map<String, List String>>

Below is the sample code

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);

I tried the below approach and with this I am not getting the required result:

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]}

Expected Result:

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

Solution

  • See the Map#compute section

    Map#compute

    Map#computeIfPresent

    Map#computeIfAbsent

    Assuming you don't want to use Multimap, something like that should do the trick.

        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;
                });
            }
        }