首页 > 文章列表 > Java中如何使用Lambda表达式实现动态条件分组?

Java中如何使用Lambda表达式实现动态条件分组?

331 2025-02-19

Java中如何使用Lambda表达式实现动态条件分组?

lambda表达式:实现动态条件分组

在java中,若想按条件对集合进行分组,可以使用collectors.groupingby方法。但有时我们需要动态地传入分组条件,比如依据某个学生属性。

为此,可以使用一个方法引用作为分组条件,如下例所示:

list.stream().collect(collectors.groupingby(student::getsex));
list.stream().collect(collectors.groupingby(student::getage));

然而,在某些情况下,我们需要动态传入分组条件,例如:

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方法按性别和年龄对学生列表进行分组。

来源:1732946498