java Lambda表达式如何按条件动态传入方法引用?

作者站长头像
站长
· 阅读数 18

java中如何按条件传入分组例如有个学生类集合,如何动态传入一个方法引用来分组?

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
}
回复
1个回答
avatar
test
2024-06-25
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());
}

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()));
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容