java Lambda表达式如何按条件动态传入方法引用?-灵析社区

皮皮踢

java中如何按条件传入分组 例如有个学生类集合,如何动态传入一个方法引用来分组? list.stream().collect(Collectors.groupingBy(Student::getSex)); list.stream().collect(Collectors.groupingBy(Student::getAge)); public List test(动态传入){ // ...list list.stream().collect(Collectors.groupingBy(动态传入)); return list }

阅读量:15

点赞量:0

问AI
public static List groupBy(List list, Function dynamicReference) { Map> groupedStudents = list.stream() .collect(Collectors.groupingBy(dynamicReference)); return groupedStudents.values().stream() .flatMap(Collection::stream) .collect(Collectors.toList()); } public static void main(String[] args) { List 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 groupedBySex = groupBy(students, Student::getSex); List groupedByAge = groupBy(students, Student::getAge); System.out.println(Arrays.toString(groupedBySex.toArray())); System.out.println(Arrays.toString(groupedByAge.toArray())); }