
lambda表达式:实现动态条件分组
在java中,若想按条件对集合进行分组,可以使用collectors.groupingby方法。但有时我们需要动态地传入分组条件,比如依据某个学生属性。
为此,可以使用一个方法引用作为分组条件,如下例所示:
list.stream().collect(collectors.groupingby(student::getsex)); list.stream().collect(collectors.groupingby(student::getage));
然而,在某些情况下,我们需要动态传入分组条件,例如:
立即学习“Java免费学习笔记(深入)”;
AI 舌诊面诊问诊医疗系统 + 诊疗商城系统源码是一套结合 AI 辅助诊断与商品转化的健康类程序,基于浩创云、ThinkPHP(PHP)开发,支持微信服务号与 H5 端,适合做中医舌诊面诊问答、健康建议推送以及配套诊疗商品的运营。
public list<student> test(动态传入){
// ...list
list.stream().collect(collectors.groupingby(动态传入));
return list
}这时,我们可以使用一个function类型的方法引用来动态传入分组条件,如下所示:
public static list<student> groupby(list<student> list, function<student, ?> dynamicreference) {
map<?, list<student>> groupedstudents = list.stream()
.collect(collectors.groupingby(dynamicreference));
return groupedstudents.values().stream()
.flatmap(collection::stream)
.collect(collectors.tolist());
}groupby方法接受两个参数:一个学生集合和一个function
在main方法中,我们可以演示使用该方法对学生列表进行分组:
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", "female", 20),
new Student("Bob", "male", 22),
new Student("Charlie", "male", 23),
new Student("Alice", "female", 21),
new Student("Bob", "male", 22)
);
List<Student> groupedBySex = groupBy(students, Student::getSex);
List<Student> groupedByAge = groupBy(students, Student::getAge);
System.out.println(Arrays.toString(groupedBySex.toArray()));
System.out.println(Arrays.toString(groupedByAge.toArray()));
}这段代码展示了如何使用groupby方法按性别和年龄对学生列表进行分组。

















