我是处理员工的ArrayList中,并通过员工的数量需要通过函数的用法组,算在职职工和计数不活动的员工。我知道如何全过程,但如何通过函数处理与组ArrayList中。
public class Employee {
private String name;
private String department;
private String status;
public Employee(String name, String department, String status) {
this.setName(name);
this.setDepartment(name);
this.setStatus(status);
}
public String getName() {
return name;
}
public String getDepartment() {
return department;
}
public void setName(String name) {
this.name = name;
}
public void setDepartment(String department) {
this.department = department;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
ArrayList<Employee> listEmployee = new ArrayList<Employee>();
listEmployee.add(new Employee("Ravi", "IT", "active"));
listEmployee.add(new Employee("Tom", "Sales", "inactive"));
listEmployee.add(new Employee("Kanna", "IT", "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 2 1 1
Sales 1 0 1
您可以使用stream()
从方法List<Employee>
获得Stream<Employee>
并使用Collectors.groupingBy(Employee::getDepartment)
由部门组Employee对象。一旦做到这一点,你会得到一个Map<String, List<Employee>>
地图对象。
该密钥将部门名称和值将是一个列表Employee
对象,现在从我们的员工可以进一步筛选的该名单不活跃和积极的员工:
System.out.println("Department total activeCount inactiveCount");
listEmployee.stream().collect(Collectors.groupingBy(Employee::getDepartment)).forEach((dept, emps) -> {
int count = emps.size();
long activeCount = emps.stream().filter(e -> "active".equals(e.getActive())).count();
long inactiveCount = emps.stream().filter(e -> "inactive".equals(e.getActive())).count();
int i = 12 - dept.length();
System.out.format(dept + "%" + i +"s" + count + "%10s" + activeCount + "%10s" + inactiveCount, " ", " ", " ");
System.out.println();
});
输出:
Department total activeCount inactiveCount
Sales 1 0 1
IT 2 1 1
它也建议使用一个枚举的活动或不活动状态,而不是一个字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句