List分组的两种方式


java8之前List分组

假设有个student类,有id、name、score属性,list集合中存放所有学生信息,现在要根据学生姓名进行分组。

 

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;
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM