以下是个人开发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();