0

I've below List<Map> as below

List<Map<String,String>> list =
                                {"key1":"1234"}
                                {"key1":"3422"}
                                {"key1":"7565"}
                                {"key2":"foo"}
                                {"key2":"bar"}
                                {"key3":"xyz"}
                                {"key4":"pqr"}

I need to convert it to a Map<String, List> as

                    {"key1":"1234","3422","7565"}
                    {"key2":"foo","bar"}
                    {"key3":"xyz"}
                    {"key4":"pqr"}
Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92
  • 1
    Does this answer your question? [Java: How to convert List to Map](https://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map) – Milgo Nov 11 '20 at 07:16
  • I don't think so.. my problem statement much different from the above given one – Swapnil Kotwal Nov 11 '20 at 12:06

1 Answers1

2
Map<String, List<String> myMap = new HashMap();
List<String> tempList = new ArrayList();
for(Map<String, String> entry : myList){
    if (myMap.contains(entry.getKey()))
        tempList = myMap.getValue();
    else
        tempList = new ArrayList();
    
    tempList.add(entry.getValue());
    myMap.put(entry.getKey(), tempList);
}
Tobi
  • 858
  • 7
  • 15
  • @Swapnil, why did you edit the answer again? Both times you changed it so it wouldn't work properly.. If you think it should be done differently, please write a comment and ask instead of changing my answer... – Tobi Nov 12 '20 at 07:06
  • `tempList` is an instance `List<>` while your assignment of `tempList = entry.getValue();` won't work. Note: `entry.getValue();` would evaluate to `String` value. – Swapnil Kotwal Dec 14 '20 at 08:10
  • @SwapnilKotwal what a heck here.. please see the update. It's not `entry.getValue()` but `myMap.getValue()` – Tobi Dec 14 '20 at 18:07
  • perfect ! looks Good – Swapnil Kotwal Dec 15 '20 at 07:01