作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经在列表中列出了数据,即姓名、性别、部门。我在列表中添加了 QA、Java、Php 等不同部门的数据。现在我必须将具有特定部门的数据放入 HashMap 中(例如,所有 QA 部门都应该动态地列在一个 ArrayList 或 List 上)。如果我添加新部门,那么它应该动态地列在新的 ArrayList 中,而不是通过硬编码。这是简单的逻辑,但我无法解决这个问题。
setter和getter
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"));
}
}
}
}
如何实现?
最佳答案
如果我没理解错的话,您想按部门对员工进行分组。
命令式的方式是
for (Employee employee: employeeList){
List<Employee> departmentList = f1soft.get(employee.getDepartment());
if (departmentList == null) {
departmentList = new ArrayList<>();
f1soft.put(emp.getDepartment(), departmentList);
}
departmentList.add(employee);
}
或者,更简单:
for (Employee employee: employeeList){
f1soft.computeIfAbsent(department, d -> new ArrayList<Employee>()).add(employee);
}
但是使用流来做这件事一定更简单:
Map<String, Employee> f1soft =
employeeList.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
请注意,我选择重命名您的类型和属性以使所有内容更具可读性。确实没有充分的理由使用 Employ 代替 Employee,或者使用 Dept 代替 Department。
关于java - 如何在 Else 条件下动态访问在 if 条件下创建的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47218765/
我是一名优秀的程序员,十分优秀!