サンプルシナリオは次のとおりです。
次のような従業員の記録があると想像してください。
name, age, salary (in 1000 dollars)
a, 20, 50
b, 22, 53
c, 34, 79
等々。目標は、さまざまな年齢層(たとえば、21〜30歳と31〜40歳など)の平均給与を計算することです。
私はこれを使用してやりたいのですが、これを行うstream
ためにどのように使用groupingBy
する必要があるのか頭を悩ませることはできません。ある種のタプルの年齢範囲を定義する必要があるのではないかと考えています。何か案は?
以下のコードはあなたが探しているものを与えるはずです。重要なのは、グループ化をサポートする「コレクター」クラスです。
Map<Double,Integer> ageGroup= employees.stream().collect(Collectors.groupingBy(e->Math.ceil(e.age/10.0),Collectors.summingInt(e->e.salary)));
給与が整数であると仮定した図ですが、2倍に簡単に切り替えることができます
完全なプログラムは次のようになります
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("a",20,100));
employees.add(new Employee("a",21,100));
employees.add(new Employee("a",35,100));
employees.add(new Employee("a",32,100));
Map<Double,Integer> ageGroup= employees.stream().collect(Collectors.groupingBy(e->Math.ceil(e.age/10.0),Collectors.summingInt(e->e.salary)));
System.out.println(ageGroup);
}
public static class Employee {
public Employee(String name, int age, int salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
public String name;
public int age;
public int salary;
}
出力は
{4.0=200, 2.0=100, 3.0=100}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加