【发布时间】:2017-11-10 08:45:50
【问题描述】:
我已经在列表中列出了数据,即姓名、性别、部门。我已经在列表中添加了不同部门的数据,如 QA、Java、Php。现在我必须将具有特定部门的数据放入哈希图中(例如,所有 QA 部门都应该动态地列在一个 ArrayList 或 List 中)。如果我添加新部门,那么它应该动态地列在新的 ArrayList 中,而不是通过硬编码。这是一个简单的逻辑,但我无法解决这个问题。
Getter 和 Setter
public class Employ {
private String name;
private int id;
private String gender;
private String dept;
public Employ(String name,int id,String gender,String dept){
this.name=name;
this.id=id;
this.gender=gender;
this.dept=dept;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the gender
*/
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* @return the dept
*/
public String getDept() {
return dept;
}
/**
* @param dept the dept to set
*/
public void setDept(String dept) {
this.dept = dept;
}
}
主类
public class App {
public static void main(String[] args) {
String key="QA";
String key2="java";
HashMap<String ,List<Employ>> soft=new HashMap();
List<Employ> employList=new ArrayList();
employList.add(new Employ("ram",1, "male","qa"));
employList.add(new Employ("tom",2, "male","qa"));
employList.add(new Employ("arjun",3, "male","java"));
employList.add(new Employ("hari",4, "male","java"));
employList.add(new Employ("kumar",5, "male","qa"));
employList.add(new Employ("sita",6, "female","java"));
employList.add(new Employ("rajan",7, "female","qa"));
employList.add(new Employ("rajal",8, "female","php"));
for(Employ emp:employList){
if(!soft.containsKey(emp.getDept())){
soft.put(emp.getDept(),new ArrayList());
}else{
// soft.put(emp.getDept(),add("qa"));
}
}
}
}
如何做到这一点?
【问题讨论】:
-
f1soft.get(emp.getDept()).add("qa"); -
您想按部门对员工进行分组,对吗? IE。有一个包含部门作为键的 Map,该部门的员工列表作为值?
-
@JBNIzet 是的,但是如果我添加到列表中,它应该也会自动添加到地图上