Reputation: 94
I have 2 arraylists(of same size) in json as below:
List<HashMap<String, String>> list1 = new Arraylist<HashMap<String, String>>();
List<HashMap<String, String>> list2 = new Arraylist<HashMap<String, String>>();
I want to merge the above lists into a single one.
For ex:
List1:
[{ " key1": "value1", " key2": "value2"},
{ " key11": "value11", " key22": "value22"}]
List2:
[{ " key3": "value3"},{" key33": "value33"}]
Expected output:
[{ " key1": "value1", " key2": "value2", " key3": "value3"},
{ " key11": "value11", " key22": "value22", " key3": "value3"}]
An early response will be highly appreciated. Thanks a lot in advance.
Upvotes: 0
Views: 92
Reputation: 2922
Edit: you can do like this
for (HashMap<String, String> m : list2) {
HashMap<String, String> t = list1.get(list2.indexOf(m));
for(String key: t.keySet()){
m.put(key, t.get(key));
}
}
Now Merged items are in list2.
Upvotes: 0
Reputation: 1345
You Just have to retrieve the Hashmap from the individual Lists and then merge them all together
for eg
HashMap m = new HashMap();
m.put("key1", "val1");
m.put("key2", "val2");
HashMap m1 = new HashMap();
m1.put("key3", "val3");
HashMap mergeMap = new HashMap();
mergeMap.putAll(m);
mergeMap.putAll(m1);
System.out.println("Map:" + mergeMap);
Output
Map:{key3=val3, key2=val2, key1=val1}
Upvotes: 0
Reputation: 61
Your expected output probably be:
[{ " key1": "value1", " key2": "value2", " key3": "value3"}, { " key11": "value11", " key22": "value22", " key33": "value33"}]
You didn't indicate whether two lists had same size or not. According to your example, I assumed the lists had same size. So the code could be like below:
for (int i = 0; i < list1.size(); i++) {
list1.get(i).putAll(list2.get(i));
}
Upvotes: 1
Reputation: 149
If the two ArrayList have the same type (they seem to be arraylist of maps):
list1.addAll(list2)
Upvotes: 2