之前见识过java 8 Lambda 的厉害,这次学习一下Java stream 用 groupingBy 进行分组,包括按单个字段分组,和按多个字段分组
1.按单个字段分组
public class MainUser{
public static void main(String[] args){
List<User> list = getUserList();
Map<String,List<User>> userGroupMap = list.stream().collect(Collectors.groupingBy(User::getType));
}
public static List<User> getUserList(){
User user1 = new User(1,"张三","小学");
User user2 = new User(2,"李四","小学");
User user3 = new User(3,"王五","初中");
User user4 = new User(4,"马六","高中");
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
return list;
}
}
输出结果:分组字段为key,被分组的list为value组成的map
{高中=[com.maps.User@448139f0], 初中=[com.maps.User@7cca494b], 小学=[com.maps.User@7ba
2.按多个字段分组
Map<String,List<User>> groupList=errorsCollectionList.stream().collect(Collectors.groupingBy(o->o.getClassId()+"_"+o.getSubjectId()));
就是把多个字段用下划线分开拼接成字符串,再分组,当然也可以先对第一个分组,再对第二个分组,这样就比较麻烦