List分組的兩種方式

java8以前List分組

假設有個student類,有id、name、score屬性,list集合中存放全部學生信息,如今要根據學生姓名進行分組。java

 

public Map<String, List<Student>> groupList(List<Student> students) {
	Map<String, List<Student>> map = new Hash<>();
	for (Student student : students) {
		List<Student> tmpList = map.get(student.getName());
		if (tmpList == null) {
			tmpList = new ArrayList<>();
			tmpList.add(student);
			map.put(student.getName(), tmpList);
		} else {
			tmpList.add(student);
		}
	}
	return map;
}

  

java8的List分組

public Map<String, List<Student>> groupList(List<Student> students) {
	Map<String, List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getName));
	return map;
}
相關文章
相關標籤/搜索