使用jdk8的stream流(基本实现分组靠Collectors.goupingby),list自带的sort()方法排序,话不多说,代码如下:
- List<User> list = Arrays.asList(new User("1","小明","2","一年级"),
- new User("2","小名","1","一年级"),
- new User("3","小刘","1","二年级"),
- new User("4","小亮","2","二年级"),
- new User("5","小项","3","三年级"),
- new User("6","小项","4","三年级"));
- Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getGrade));
- System.out.println("排序前已完成分组: ");
- System.out.println(collect.toString());
- collect.values().forEach(item -> {
- item.sort((o1, o2) -> Integer.parseInt(o1.getSorted()) - Integer.parseInt(o2.getSorted()));
- });
- System.out.println("排序后:");
- System.out.println(collect.toString());
输出结果如下
- 排序前已完成分组:
- {一年级=[User{id='1', name='小明', sorted='2', grade='一年级'}, User{id='2', name='小名', sorted='1', grade='一年级'}], 三年级=[User{id='5', name='小项', sorted='3', grade='三年级'}, User{id='6', name='小项', sorted='4', grade='三年级'}], 二年级=[User{id='3', name='小刘', sorted='1', grade='二年级'}, User{id='4', name='小亮', sorted='2', grade='二年级'}]}
- 排序分组后:
- {一年级=[User{id='2', name='小名', sorted='1', grade='一年级'}, User{id='1', name='小明', sorted='2', grade='一年级'}], 三年级=[User{id='5', name='小项', sorted='3', grade='三年级'}, User{id='6', name='小项', sorted='4', grade='三年级'}], 二年级=[User{id='3', name='小刘', sorted='1', grade='二年级'}, User{id='4', name='小亮', sorted='2', grade='二年级'}]}