Reputation: 3
I have 2 ArrayList < HashMap < String, String>>
.
list1: [{name=Alice, count=193}, {name=Bob, count=13}, {name=Charlie, count=179}, ...]
list2: [{name=Alice, change=1}, {name=Bob, change=15}, {name=Jimmy, change=15}, ...]
All key values present in list2
are present in list1
, but not vice versa. For eg. since Charlie has 0 change, he is not present in list2
. I want to merge these 2 lists based on the key values (name) to create a new list3
.
list3: [{name=Alice, count=193, change=1}, {name=Bob ,count=13, change=15}, {name=Charlie, count=179, change=0}, ...]
Upvotes: 0
Views: 737
Reputation: 458
Assuming list1
and list2
do not contain duplicate name
s you can do something like this:
//list3 created.
for(HashMap<String,String> hm2:list2){
String nameValue=hm2.get("name");
for(HashMap<String,String> hm1:list1){
if(hm1.get("name").equalsIgnoreCase(nameValue)){
HashMap<String,String> tempMap = new HashMap();
tempMap.put("name",nameValue);
tempMap.put("count",hm1.get("count"));
tempMap.put("change",hm2.get("change"));
list3.add(tempMap);
break;
}
}
}
System.out.println(list3);
Upvotes: 2
Reputation: 1
You can:
1/ create a class called Account
which contains name
, count
, change
, then the result would be a list of Account
(if you dont want to create a new class, you can skip this step)
2/ from list2
build a HashMap<String (name), Integer (change)>
3/ iterate through the list1
, which every element, find a corresponding change
base on the HashMap
built in step 2, then build an Account
(or a HashMap
which contains all the info), add the account (or the HashMap
) to list3
Upvotes: 0