list数据实现先分组后排序

使用jdk8stream流(基本实现分组靠Collectors.goupingby),list自带的sort()方法排序,话不多说,代码如下:

  1.  
    List<User> list = Arrays.asList(new User("1","小明","2","一年级"),
  2.  
    new User("2","小名","1","一年级"),
  3.  
    new User("3","小刘","1","二年级"),
  4.  
    new User("4","小亮","2","二年级"),
  5.  
    new User("5","小项","3","三年级"),
  6.  
    new User("6","小项","4","三年级"));
  7.  
    Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getGrade));
  8.  
    System.out.println("排序前已完成分组: ");
  9.  
    System.out.println(collect.toString());
  10.  
    collect.values().forEach(item -> {
  11.  
    item.sort((o1, o2) -> Integer.parseInt(o1.getSorted()) - Integer.parseInt(o2.getSorted()));
  12.  
    });
  13.  
    System.out.println("排序后:");
  14.  
    System.out.println(collect.toString());

输出结果如下

  1.  
    排序前已完成分组:
  2.  
    {一年级=[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='二年级'}]}
  3.  
    排序分组后:
  4.  
    {一年级=[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='二年级'}]}
 
posted @ 2023-07-19 13:58  甜菜波波  阅读(232)  评论(0编辑  收藏  举报