gpt4 book ai didi

java - 如何在 Else 条件下动态访问在 if 条件下创建的 ArrayList?

转载 作者:行者123 更新时间:2023-11-29 07:28:15 25 4
gpt4 key购买 nike

我已经在列表中列出了数据,即姓名、性别、部门。我在列表中添加了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com