0

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}, ...]

2
  • Why are you using a list of key-value pairs? Shouldn't you be using a simple Map instead? Commented Nov 24, 2017 at 2:57
  • The data is from a json source so i just parsed it and put it into a HashMap Commented Nov 24, 2017 at 3:11

2 Answers 2

2

Assuming list1 and list2 do not contain duplicate names 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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.