Java Stream用法汇总

本文分享了Java开发者在处理BigDecimal数据时的stream操作技巧,包括汇总、分组以及多个字段组合,帮助读者理解如何优雅地处理数值计算和数据整理。

以下是个人开发Java代码时候,使用的一些stream方法,做记录方便查询。

stream对BigDecimal汇总

注意,如果不加过滤条件,可能出现空指针错误

 BigDecimal totalAmount = hzPropertyList.stream()
                    .filter(item -> item.getAmount() != null)
                    .map(HzProperty::getAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

stream对BigDecimal按单个分组汇总

   Map<String, BigDecimal> companyPropertyMap = hzPropertyList.stream() 
                .collect(Collectors.groupingBy(
                        HzProperty::getCodeCompany,
                        Collectors.reducing(BigDecimal.ZERO, HzProperty::getAmount, BigDecimal::add))

stream多个字段分组

Map<String, List<HzProperty>> companyPropertyMap = hzPropertyList.stream()
                .collect(Collectors.groupingBy(hzProperty -> String.format("%s#%s", hzProperty.getCodeCompany(), hzProperty.getCurrencyCode())));

stream按数量拆分成多个List

List<String> sourceLineIds = new ArrayList<>(map.keySet());    
long splitSize = 1000;
int maxSize = (int) Math.ceil((double) sourceLineIds.size() / (double) splitSize);
List<List<String>> sourceLineIdsList = Stream.iterate(0, n -> n + 1)
                .limit(maxSize)
                .map(a -> sourceLineIds.stream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList()))
                .collect(Collectors.toList());

 stream查找最大值所在的行

adjustJeLine = jeLineList.stream()
                            .filter(jeLine -> jeLine.getAccountedDr() != null)
                            .max(Comparator.comparing(jeLine -> jeLine.getAccountedDr().abs()))
                            .orElse(new JeLine());

 stream对List<Interger>汇总

int sum =  list.stream().mapToInt(Integer::intValue).sum();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值