Java8 Stream分组并排序

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Customer {

    private String name;
    private TypeEnum type;
    private int age;
}

@Getter
public enum TypeEnum {

    /**
     * 第一
     */
    First("甲类", 2),
    Second("乙类", 12),
    Three("丙类",0),
    Four("丁类",3),
    ;
    private String desc;
    /**
     * 优先级
     */
    private int priority;

    TypeEnum(String desc, int priority) {
        this.desc = desc;
        this.priority = priority;
    }
}

public class GroupByTest {

    @Test
    public void test() {
        List<Customer> customers = new ArrayList<>();
        // 按照type 分组,组内 age 排序
        customers.add(new Customer("张三", TypeEnum.First, 18));
        customers.add(new Customer("赵六", TypeEnum.Second, 25));
        customers.add(new Customer("李四", TypeEnum.Second, 22));
        customers.add(new Customer("张一", TypeEnum.Three, 31));
        customers.add(new Customer("王五", TypeEnum.Four, 45));
        customers.add(new Customer("张二", TypeEnum.Four, 40));
        // 如此分组,treeMap 默认排序会按照 TypeEnum 枚举顺序
        TreeMap<TypeEnum, List<Customer>> treeMap = customers.stream().collect(Collectors.groupingBy(Customer::getType, TreeMap::new, Collectors.toList()));
        System.out.println("默认排序:" + treeMap);

        // 如果 treeMap 想要自定义排序,则可以这么做
        TreeMap<TypeEnum, List<Customer>> treeMap2 = customers.stream().collect(Collectors.groupingBy(Customer::getType, GroupByTest::getCustomSortTreeMap, Collectors.toList()));

        for (Map.Entry<TypeEnum, List<Customer>> entry : treeMap2.entrySet()) {
            entry.getValue().sort(Comparator.comparing(Customer::getAge));
        }

        System.out.println("自定义排序:" + treeMap2);

        // 按指定字段分组
        Map<TypeEnum, List<Integer>> map3 = customers.stream().collect(Collectors.groupingBy(Customer::getType,
                Collectors.mapping(Customer::getAge, Collectors.toList())));

        System.out.println("按指定字段分组:" + map3);

        TreeMap<TypeEnum, List<Customer>> treeMap4 = customers.stream().sorted(Comparator.comparing(Customer::getAge, Comparator.nullsLast(Integer::compareTo)))
                .collect(Collectors.groupingBy(Customer::getType, TreeMap::new, Collectors.toList()));
        System.out.println("排序后分组:" + treeMap4);

    }


    public static TreeMap<TypeEnum, List<Customer>> getCustomSortTreeMap() {
        return new TreeMap<>(Comparator.comparingInt(TypeEnum::getPriority));
    }

以上是使用分组排序的一些测试,初学不建议深究原理,作为 API使用即可

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值