JDK8 stream sort排序,groupingBy分组

本文介绍了如何使用JDK8的Stream API进行排序和分组操作。首先展示了如何处理排序字段可能为null的情况,通过Comparator.nullsFirst进行排序。接着详细说明了Collectors.groupingBy方法,用于根据对象属性进行分组,并举例演示了单级和多级分组的用法。此外,还讨论了在分组基础上如何进行聚合操作,如求总数、求和以及转换收集器结果。
摘要由CSDN通过智能技术生成

创建排序字段带null的List(排序字段为User.name)

List<User> nList = list.stream().sorted( Comparator.comparing(User::getName, Comparator.nullsFirst(String::compareTo))) .collect(Collectors.toList());

Comparator.nullsFirst 排序字段为null的对象放在排序后的List最后面
Comparator.nullsLast 排序字段为null的对象放在排序后的List最前面

Collectors.groupingBy根据一个或多个属性对集合中的项目进行分组

数据准备:

public Product(Long id, Integer num, BigDecimal price, String name, String category) {
	this.id = id;
	this.num = num;
	this.price = price;
	this.name = name;
	this.category = category;
}

Product prod1 = new Product(1L, 1, new BigDecimal("15.5"), "面包", "零食");
Product prod2 = new Product(2L, 2, new BigDecimal("20"), "饼干", "零食");
Product prod3 = new Product(3L, 3, new BigDeci
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值