Can someone help me to code for merging equal sized map of list into a list of map?
Ex: Input
Map<String, List<Object>> map = new HashMap<>();
map.put("userid", Arrays.asList(1, 2, 3));
map.put("username", Arrays.asList("a","b","c"));
map.put("country", Arrays.asList("UK","IN","US"));
{country=[UK, IN, US], userid=[1, 2, 3], username=[a, b, c]}
.. and list goes on with any number of maps.
Desired output in JSON:
[
{"userid":1, "username":"a", "country":"UK"},
{"userid":2, "username":"b", "country":"IN"},
{"userid":3, "username":"c", "country":"US"}
]
I checked this post but it has all the combinations. I am looking something like 1:1 mapping.
Tried with below approach. Might not be the right way and appreciate if someone can help with a better solution.
ArrayList<Object> myList = new ArrayList<>();
int mapSize = map.get("userid").size();
for (int i=0; i< mapSize; i++) {
Map<String,Object> eachMap = new HashMap<>();
for (String key : map.keySet())
//System.out.println(key + "," + map.get(key).get(i));
eachMap.put(key,map.get(key).get(i));
myList.add(eachMap);
}
JSONArray jsonArray = new JSONArray();
jsonArray.addAll(myList);
System.out.println(jsonArray);
Output
[{"country":"UK","userid":1,"username":"a"},{"country":"IN","userid":2,"username":"b"},{"country":"US","userid":3,"username":"c"}]