Search code examples
javaarraylistdata-structureshashmap

How to merge the list of values to the same Key in HashMap?


How to merge the list of values to the same key in HashMap?

If I use the above logic I'm getting below result as an output:

{Adam=[[Subject, ComputerScience], [Subject, ComputerScience]]}

But I have to merge like the below result, is it possible to append the list of values to the same key?

{Adam=[Subject, ComputerScience, Subject, ComputerScience]}


Example

public class DemoMap {

    public static void main(String[] args) {
        ArrayList<String> mngrList1 = new ArrayList<>();
        mngrList1.add("Jay");
        mngrList1.add("Aaron");
        
        // Adam is Senior Manager who has the list of managers under him
        HashMap<String, ArrayList<String>> tmeMap = new HashMap<>();
        tmeMap.put("Adam", mngrList1);

        ArrayList<Object> emailContent = new ArrayList<>();
        emailContent.add("Subject");
        emailContent.add("ComputerScience");
        
        HashMap<String, ArrayList<Object>> mngrMap = new HashMap<>();
        mngrMap.put("Jay", emailContent);
        mngrMap.put("Aaron", emailContent);

        // Each manager will have the email content       
        ArrayList<Object> collectionOfManagerContent = new ArrayList<>();
        for (Map.Entry<String,ArrayList<Object>> emailEntry : mngrMap.entrySet()) {
            collectionOfManagerContent.add(emailEntry.getValue());
        }

        // Our goal is to show the manager's content to Senior Project manager      
        HashMap<String, ArrayList<Object>> tmeEmailMap1 = new HashMap<>();
        for (Map.Entry<String,ArrayList<String>> emailEntry : tmeMap.entrySet()) {
            emailEntry.getValue();
            tmeEmailMap1.put(emailEntry.getKey(), collectionOfManagerContent);
        }
        System.out.println(tmeEmailMap1.toString());
    }

}

Solution

  • Use addAll() to add all elements of ArrayList into another ArrayList

    for (Map.Entry<String,ArrayList<Object>> emailEntry : mngrMap.entrySet()) {
        collectionOfManagerContent.addAll(emailEntry.getValue());
    }