一、简介:
Java8中的groupBy实现集合的分组,类似Mysql的group by分组功能,注意得到的结果是一个map
二、代码测试案例:
package demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import entity.Student;
/**
* @author :zkx
* @createtime :2020年3月17日 下午4:46:31
* @description:
*/
public class Test03 {
public static void main(String[] args){
List<Student> list = new ArrayList<>();
Student Student1 = new Student("1", "张三", "10");
Student Student2 = new Student("2", "张三", "11");
Student Student3 = new Student("3", "张三", "12");
Student Student4 = new Student("4", "李四", "13");
Student Student5 = new Student("5", "李四", "14");
Student Student6 = new Student("6", "李四", "15");
Student Student7 = new Student("7", "王五", "16");
Student Student8 = new Student("8", "王五", "17");
Student Student9 = new Student("9", "王五", "18");
list.add(Student1);
list.add(Student2);
list.add(Student3);
list.add(Student4);
list.add(Student5);
list.add(Student6);
list.add(Student7);
list.add(Student8);
list.add(Student9);
// 根据学生的名字Name进行分组
Map<String,List<Student>> StudentGroupMap = list.stream().
collect(Collectors.groupingBy(Student::getName));
// 分组结果
System.out.println("分组后的数据:" + StudentGroupMap);
System.out.println();
// 循环查看分组后对应的的数据信息
Set<String> keySet = StudentGroupMap.keySet();
keySet.forEach((key)->{
System.out.println(key);
StudentGroupMap.get(key).
forEach((Student)->
System.out.println(Student));
});
}
}