Java 8 Stream 的使用

本文详细介绍了如何使用Java集合API进行数据处理,包括对象属性的去重、转换、求和、过滤、分组等操作,以及在实际场景中的应用,如统计、求和、字符串拼接等。通过实例展示了Java 8的流处理能力,揭示了其在数据处理上的高效和便捷。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 将couponList集合中的CouponVo对象里的属性couponId,去重并转换成字符串
    (1)去重:.distinct()
    (2)转换成字符串:.collect(Collectors.joining(“,”))
String couponId = couponList.stream().map(CouponVo::getCouponId).distinct().collect(Collectors.joining(","));
  1. 将payList集合中的RechargePayItem对象里的属性amount,求和并且类型为INT
    (1)求和:.sum()
    (2)Int类型:.mapToInt(RechargePayItem::getAmount)
Integer total = payList.stream().mapToInt(RechargePayItem::getAmount).sum();
  1. 将couponList集合中的CouponVo对象里的符合条件(couponNumber不为空),组成新的List集合
    (1)条件筛选:.filter(item->null != item.getCouponNumber())
    (2)添加到新List:.collect(Collectors.toList())
List<CouponVo> couponNumberNotNullList = couponList.stream().filter(item->null != item.getCouponNumber()).collect(Collectors.toList());
  1. 将listPerson集合中符合条件的数据组装成需要的字符串
for (RechargeOrderDetail item: pageList) {
	//拼装数据
	String sellVipPersonJSON = listPerson.stream()
		.filter(person -> item.getPaymentId().equals(person.getPaymentId()))
		.map(person->{
		    return StrUtil.isNotBlank(person.getSellJobNum()) && !"0".equals(person.getSellJobNum())
		    ?"("+person.getSellJobNum()+")"+person.getSellName()
		    :(StrUtil.isNotBlank(person.getSellName())?person.getSellName():null);
		})
		.collect(Collectors.joining(","));
	//将拼装好的字符串赋值给对象
	item.setSellVipPerson(sellVipPersonJSON);
}
  1. 将payItemList集合中的RechargePayItem对象里的属性payType,去重并计算个数
    (1)去重:.distinct()
    (2)个数:.count()
long listSize = payItemList.stream().map(RechargePayItem::getPayType).distinct().count();
  1. 将pageList集合中的WorkNextConfig对象里的属性next,进行分组并转换成字符串
    (1)分组:.collect(Collectors.groupingBy(p -> p.getNext(), Collectors.toList()))
Map<String, List<WorkNextConfig>> collect = pageList.stream().collect(Collectors.groupingBy(p -> p.getNext(), Collectors.toList()));
collect.forEach((key, value) -> {
	WorkNextConfig workNextConfig = new WorkNextConfig();
	String department =value.stream().map(item->String.valueOf(item.getOrgid())).collect(Collectors.joining(","));
    workNextConfig.setDepartment(department);
});
  1. 将dataList集合中的WorkTaskContent对象里的属性fgrade不为空,则进行求和
    (1)条件:.filter(w->null != w.getFgrade())
    (2)计算分值:.map(w -> w.getWeight().multiply(w.getFgrade()).divide(new BigDecimal(100)))
    (3)求和:.reduce(BigDecimal.ZERO,BigDecimal::add)
BigDecimal fgradeTotal = dataList.stream().filter(w->null != w.getFgrade()).map(w -> w.getWeight().multiply(w.getFgrade()).divide(new BigDecimal(100))).reduce(BigDecimal.ZERO,BigDecimal::add);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值