Search code examples
javadictionarygrails

Push values to a map when key is already exisitng in a map


I have declared a map as below:

 Map<String, String[]> test = new HashMap<String, String[]>();

I have a variable empnames which is an array and deptname is a String and i have declared the deptname and empnames as below:

 String deptname = ['Department']
 String empnames = [['Test1']['Test2']]

 if (deptname != null)
        {
            if (test.containsKey(deptname))
                {
                    ///
                }
                else
                {

                    test.put(deptname, new String[]{empnames}); 
                }
            }

If the test map already contains deptname key then what condition i should write in if condition to append new values to department?


Solution

  • ArrayList<String> departmentList;
        if(test.containsKey(key)){
            // if the key has already been used, then and add a new value to it
            list = test.get(key);
            list.add(value);
            test.put(key, list);
        } else {
            // if the key hasn't been used yet, then create a new ArrayList<String> object, add the value
            list = new ArrayList<String>();
            list.add(value);
            test.put(key, list);
        }