在Java8中,可以使用Collectors.groupingBy
方法對List集合根據屬性進行分組。以下是一個完整的示例,展示如何根據對象的不同屬性分組。
根據對象屬性分組
假設有一個Student
類,包含name
、age
和grade
屬性:
public class Student {private String name;private int age;private String grade;// 構造方法、Getter和Setter省略
}
按單一屬性分組(如grade)
List<Student> students = Arrays.asList(new Student("Alice", 20, "A"),new Student("Bob", 21, "B"),new Student("Charlie", 20, "A")
);Map<String, List<Student>> groupedByGrade = students.stream().collect(Collectors.groupingBy(Student::getGrade));System.out.println(groupedByGrade);
輸出結果:
{A=[Student{name='Alice', age=20, grade='A'}, Student{name='Charlie', age=20, grade='A'}],B=[Student{name='Bob', age=21, grade='B'}]
}
按多個屬性分組(復合鍵)
如果需要根據多個屬性分組(如age
和grade
),可以使用Collectors.groupingBy
結合復合鍵:
Map<List<Object>, List<Student>> groupedByAgeAndGrade = students.stream().collect(Collectors.groupingBy(student -> Arrays.asList(student.getAge(), student.getGrade())));System.out.println(groupedByAgeAndGrade);
輸出結果:
{[20, A]=[Student{name='Alice', age=20, grade='A'}, Student{name='Charlie', age=20, grade='A'}],[21, B]=[Student{name='Bob', age=21, grade='B'}]
}
分組后計算(如計數、求和)
可以使用Collectors.groupingBy
結合其他收集器進行聚合操作:
// 按grade分組并計算每組的數量
Map<String, Long> countByGrade = students.stream().collect(Collectors.groupingBy(Student::getGrade,Collectors.counting()));System.out.println(countByGrade); // 輸出:{A=2, B=1}
分組后映射(提取特定屬性)
// 按grade分組并提取name列表
Map<String, List<String>> namesByGrade = students.stream().collect(Collectors.groupingBy(Student::getGrade,Collectors.mapping(Student::getName, Collectors.toList())));System.out.println(namesByGrade); // 輸出:{A=[Alice, Charlie], B=[Bob]}
并行流分組
對于大數據集,可以使用并行流提高性能:
Map<String, List<Student>> parallelGrouped = students.parallelStream().collect(Collectors.groupingBy(Student::getGrade));
以上方法涵蓋了Java8中對List集合按屬性分組的常見場景,包括單一屬性、復合鍵分組以及分組后的聚合操作。