Map<String, List<User>> userMap = list.stream().collect(Collectors.groupingBy(User::getGroup));
示例:
public class HelloWorld { public static void main(String[] args) { Random random = new Random(); List<User> list = new ArrayList<>(); for(int i=1;i<=20;i++) { String group = (random.nextInt(3) + 1) + "组";//1-3组随机 User u = new User(i, "用户-" + i, group); list.add(u); } //按group属性分组 Map<String, List<User>> userMap = list.stream().collect(Collectors.groupingBy(User::getGroup)); System.out.println("分组后:" + userMap); } private static class User{ Integer id; String name; String group; public User(Integer id, String name, String group) { this.id = id; this.name = name; this.group = group; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '/'' + ", group='" + group + '/'' + '}'; } } }
执行结果:
{ 3 组 = [User { id = 2, name = '用户-2', group = '3组' }, User { id = 5, name = '用户-5', group = '3组' }, User { id = 7, name = '用户-7', group = '3组' }, User { id = 8, name = '用户-8', group = '3组' }, User { id = 9, name = '用户-9', group = '3组' }, User { id = 12, name = '用户-12', group = '3组' }, User { id = 13, name = '用户-13', group = '3组' }, User { id = 15, name = '用户-15', group = '3组' }, User { id = 16, name = '用户-16', group = '3组' }], 2 组 = [User { id = 1, name = '用户-1', group = '2组' }, User { id = 17, name = '用户-17', group = '2组' }, User { id = 18, name = '用户-18', group = '2组' }, User { id = 20, name = '用户-20', group = '2组' }], 1 组 = [User { id = 3, name = '用户-3', group = '1组' }, User { id = 4, name = '用户-4', group = '1组' }, User { id = 6, name = '用户-6', group = '1组' }, User { id = 10, name = '用户-10', group = '1组' }, User { id = 11, name = '用户-11', group = '1组' }, User { id = 14, name = '用户-14', group = '1组' }, User { id = 19, name = '用户-19', group = '1组' }] }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16947.html