
lambda表达式:实现动态条件分组
在java中,若想按条件对集合进行分组,可以使用collectors.groupingby方法。但有时我们需要动态地传入分组条件,比如依据某个学生属性。
为此,可以使用一个方法引用作为分组条件,如下例所示:
list.stream().collect(collectors.groupingby(student::getsex)); list.stream().collect(collectors.groupingby(student::getage));
然而,在某些情况下,我们需要动态传入分组条件,例如:
立即学习“Java免费学习笔记(深入)”;
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<student, ?>类型的动态分组条件。它返回一个按动态条件分组的学生集合列表。
在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方法按性别和年龄对学生列表进行分组。
以上就是Java中如何使用Lambda表达式实现动态条件分组?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号