0

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?

roeygol
  • 4,908
  • 9
  • 51
  • 88
ha9u63a7
  • 6,233
  • 16
  • 73
  • 108

2 Answers2

2

This is definitely doable. It looks like you are implementing a many-to-many relationship between employees and projects. This would correspond to a pair of tables with a junction table to connect them.

Your would read your employees and your projects, and then add projects to each employee set.

I should mention that it's not a good idea to expose a set as a member variable, because sets are mutable. You could make the variable private, and expose methods to add/query projects from your object.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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
 }
kamoor
  • 2,909
  • 2
  • 19
  • 34