cbbeginner:
私は、従業員の配列リストを処理し、従業員の数によって機能の使用状況によってグループを必要とする、アクティブな従業員をカウントし、非アクティブな従業員をカウントしました。私は、合計の処理方法を知っているが、値が配列の文字列であるときにどのように私は、機能によってグループとのArrayListを処理することができ、すなわち、1つの従業員が複数の部門に関連付けられています。
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
シャロンベンアッシャー:
まず、各部門のカウンタを保持するクラスを作成する必要があります。
(インスタンス変数が行われた以下のボード線図のようなものpublic
簡潔にするため)。equals()
そしてhashCode()
私たちは、Aには、このクラスのインスタンスを置くしようとしているので、必要とされています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<>();
今、それがマップから適切なエントリを取り、部門のリストの上に、反復従業員の各項目のリストを反復処理の簡単な問題であり、カウンタを蓄積(バックマップに置くこと):
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);
}
}