1 User实体类
public class User {private Long userId;/*** 用户名(登录)*/private String username;/*** 年龄*/private int age;/*** 性别*/private int sex;/*** 密码*/private String password;}
2 单字段分组
//根据年龄分组List<User> userList = new ArrayList<>();//方法引用实现Map<Integer, List<User>> ageGroupMap = userList.stream().collect(Collectors.groupingBy(User::getAge));//lambda表达式实现Map<Integer, List<User>> ageGroupMap2 = userList.stream().collect(Collectors.groupingBy(x->x.getAge()));
3 多字段分组
//根据年龄和性别分组List<User> userList = new ArrayList<>();//lambda表达式实现Map<String, List<User>> ageGroupMap = userList.stream().collect(Collectors.groupingBy(x -> x.getAge() + "#" + x.getSex()));
分完组之后key是这几个拼成的string。