java Lambda表达式如何按条件动态传入方法引用?
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
}
回答:
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()));
}
回答:
参数传一个Function,代码如下
public static Map<String, List<Student>> process(Function<Student, String> function) { List<Student> studentList = new ArrayList<>();
Map<String, List<Student>> map = studentList.stream().collect(Collectors.groupingBy(function));
return map;
}
public static void main(String[] args) {
Map<String, List<Student>> map=process(Student::getName);
}
以上是 java Lambda表达式如何按条件动态传入方法引用? 的全部内容, 来源链接: utcz.com/p/945376.html