我正在处理员工的数组列表,并且需要按员工人数,活动员工数和非活动员工数按功能使用分组。我知道如何处理总数,但是当值在数组字符串中时(即一名员工与多个部门关联),如何按功能按组处理数组列表。
public class Employee {
private String name;
private List<String> department;
private String status;
public Employee(String name, List<String> department, String status) {
this.setName(name);
this.setDepartment(department);
this.setStatus(status);
}
public String getName() {
return name;
}
public List<String> getDepartment() {
return department;
}
public void setName(String name) {
this.name = name;
}
public void setDepartment(List<String> department) {
this.department = department;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
ArrayList<Employee> listEmployee = new ArrayList<Employee>();
List<String> listString1 = Arrays.asList("IT", "Sales");
List<String> listString2 = Arrays.asList("Sales");
List<String> listString3 = Arrays.asList("Sales");
listEmployee.add(new Employee("Ravi", listString1, "active"));
listEmployee.add(new Employee("Tom", listString2, "inactive"));
listEmployee.add(new Employee("Kanna", listString3, "inactive"));
int count = 0;
for (Employee e : listEmployee) {
count++;
}
System.out.println("Count of Employees" + count);
这是我试图获取员工人数的上述代码
int count = 0;
for (Employee e : listEmployee) {
count++;
}
System.out.println("Count of Employees" + count);
请按部门分组帮助我处理数据
我期望以下输出:
Department total activeCount inactiveCount
IT 1 1 0
Sales 3 1 2
答案 0 :(得分:5)
首先,我们需要创建一个类,其中包含每个部门的计数器。
类似于下面的预兆(为简洁起见,将实例变量设为public
)。我们需要将此类的实例放入equals()
hashCode()
和Map
public class DepartmentStats {
public String name;
public int total = 0;
public int activeCount = 0;
public int inactiveCount = 0;
public DepartmentStats() {}
public DepartmentStats(String name) {
this.name = name;
}
/**
* equality based on dept name
*/
@Override
public boolean equals(Object other) {
return other instanceof DepartmentStats &&
this.name.equals(((DepartmentStats) other).name);
}
/**
* hash code based on dept name
*/
@Override
public int hashCode() {
return name.hashCode();
}
}
第二,我们将创建一个地图,该地图将使我们能够按部门对员工进行分组并保存累积计数器
Map<String, DepartmentStats> departmentStatsMap = new HashMap<>();
现在,直接遍历员工列表是一件简单的事情,对于每个项目,遍历部门列表,从地图上获取适当的条目并累积计数器(然后放回地图):< / p>
for (Employee employee : listEmployee) {
for (String departmentName : employee.getDepartment()) {
DepartmentStats departmentStats = departmentStatsMap.get(departmentName);
if (departmentStats == null) departmentStats = new DepartmentStats(departmentName);
departmentStats.total++;
if (employee.getStatus().equals("active")) departmentStats.activeCount++;
if (employee.getStatus().equals("inactive")) departmentStats.inactiveCount++;
departmentStatsMap.put(departmentName, departmentStats);
}
}