Search code examples
javaaggregationcompositionclass-diagramjava-collections-api

Set<T> within a Map<K,V> in Java


I was wondering if it is possible to have a Set member added as a member variable of a class, the object of which can then be put as a value into a Map.

My idea is to use HashSet<T> projects as a member variable for my employee class. But, I would like to have a query performed on a database that will return query results as a Map> item where int will be the employeeId and Set will be the projects. is it doable at all?


Solution

  • Try something like this

    class Project{
         int pid;
         int name;
         //Getter and setter
    }
    

    Create Employee class

    public class Employee {
         int employeeId;
         String name;
         Set<Project> projects;
         //getter , setter  or add methods
    }
    

    Now you can use above two classes in DAO

    public class EmployeesDao{
    
     /* Get multiple employee-projects */
     public Map<Integer, Set<Project>> getManyEmployeeAndProjects(){
        Map<Integer, Set<Project>> emps = new HashMap<Integer, Set<Project>>();
        //query and populate 
        return emps;
    
     }
     /**
      * Get single employee
      */
     public Employee getEmployee(){
        //Query and return Employee
        return new Employee();
     }
    }
    

    That being said, I think you may only need return list of employees because Employee will have employee id and projects

     public List<Employee> getEmployees(){
       //create list of Employee object
     }