简体   繁体   中英

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?

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.

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
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM