どのように私は、ArrayListの機能により、カウント、およびグループを処理することができます

CBのRAK:

ここでは、画像の説明を入力します。私は、従業員の配列リストを処理し、従業員の数によって機能の使用状況によってグループを必要とする、アクティブな従業員をカウントし、非アクティブな従業員をカウントしました。私は、合計を処理する方法を知っているが、どのように私は機能によってグループでの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

また、使用することをお勧めします列挙型をアクティブまたは非アクティブの状態ではなく、文字列のために。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=236450&siteId=1