Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The HashMap class only allows you to store one value with each key. One way arou

ID: 3606916 • Letter: T

Question

The HashMap class only allows you to store one value with each key. One way around this is to store a list associated with a key. This way, you can store multiple values at the same key.

Write a method that take as parameters this kind of map, a new key, and a new value. In this example, the keys are the name of an employee's department. The value is the Employee object.

In this method, check to see if the value is already in the table (meaning included in the list for that key). If it's already there, don't add it again. If it's not there, add it to the list.

The method header is: public void addToMap(HashMap<String, List<Employee>> map, String employeeDepartment, Employee emp)

Explanation / Answer

JAVA CODE for addToMap method:

public static void addToMap(HashMap<String, List<Employee>> map, String employeeDepartment, Employee emp)

{

                //if map already contains the key,

// append the next Employee to the list value of that key

                if(map.containsKey(employeeDepartment))

                {

                                List<Employee> l = map.get(employeeDepartment);

                                if(!l.contains(emp))

                                {

                                                l.add(emp);

                                                map.put(employeeDepartment, l);

                                }

                               

                }

//else, add the new < employeeDepartment,l> pair to the map

// where l contains only a single employee emp

                else

                {

                                List<Employee> l = new ArrayList<Employee>();

                                l.add(emp);

                                map.put(employeeDepartment, l);

                }

}

  

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote