Java ListのGroupByとは? 実践的な使い方と注意点

Javaでは、Listをグループ化するために、Stream APIのCollectors.groupingBy()メソッドを使用することができます。このメソッドは、グループ化の基準を定義するためにFunctionを受け入れ、その後Mapオブジェクトを返します。そのMapオブジェクトのkeyはグループ化の基準であり、valueはそのグループに属する要素のリストです。

以下は、Collectors.groupingBy()メソッドを使用してリストをグループ化する方法を示す簡単な例です。

もしStudentクラスがあると仮定します。

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

その後、リストがあります。

List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 22));
students.add(new Student("Alice", 21));
students.add(new Student("Charlie", 20));

現在、Studentの名前属性に従ってグループ化したい。

Map<String, List<Student>> groupedStudents = students.stream()
    .collect(Collectors.groupingBy(Student::getName));

これにより、キーがStudentのnameプロパティの値で、値がそのグループに属するStudentオブジェクトのリストであるMapオブジェクトが得られます。

上記の例では、groupedStudentsの結果は以下のようになる可能性があります:

{
    "Alice": [Student{name='Alice', age=20}, Student{name='Alice', age=21}],
    "Bob": [Student{name='Bob', age=22}],
    "Charlie": [Student{name='Charlie', age=20}]
}
bannerAds