1 这个是分组的方法,根据 Student的name对 List<Student>进行分组,最后返回一个Map,键值为name。
private Map<String, List<Student>> buildMap(List<Student> students) {
Map<String, List<Student>> studentMap = new HashMap<>();
for (Student student: students) {
List<Student> tempList = studentMap .get(studentMap.getName());
if (tempList == null) {
tempList = newArrayList();
tempList.add(student);
studentMap.put(student.getName(), tempList);
}else{
tempList.add(student);
}
}
return studentMap;
}
2 采用java8中的流操作stream
private Map<String, List<Student>> buildMap(List<Student> students) {
return students.stream().collect(Collectors.groupingBy(Student::getName));
}