stream对多个字段分组_Java stream 用 groupingBy 进行多字段分组

之前见识过java 8 Lambda 的厉害,这次学习一下Java stream 用 groupingBy 进行分组,包括按单个字段分组,和按多个字段分组

1.按单个字段分组

public class MainUser{

public static void main(String[] args){

List list = getUserList();

Map> userGroupMap = list.stream().collect(Collectors.groupingBy(User::getType));

}

public static List getUserList(){

User user1 = new User(1,"张三","小学");

User user2 = new User(2,"李四","小学");

User user3 = new User(3,"王五","初中");

User user4 = new User(4,"马六","高中");

List list = new ArrayList();

list.add(user1);

list.add(user2);

list.add(user3);

list.add(user4);

return list;

}

}

输出结果:分组字段为key,被分组的list为value组成的map

{高中=[com.maps.User@448139f0], 初中&

你可能感兴趣的:(stream对多个字段分组)