Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
            });
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading