java 嵌套类 map,Java 8:具有列表嵌套类的收集器groupby

I am trying to get following Map via Java 8

Class One {

String one;

List two;

}

Class Two {

BigDecimal bd;

}

How do I collect a Map which contains grouping by One.one i.e., first parameter of map. For second parameter of map sum of Two.bd.

解决方案

You can use this:

List list = ...;

Map result1 = list.stream()

.collect(Collectors.groupingBy(One::getOne, // key is One.one

Collectors.mapping(one -> one.getTwo().stream() // get stream of One.two

.map(Two::getBd) // map to Bd

.reduce(BigDecimal.ZERO, BigDecimal::add), // reduce to sum

Collectors.reducing(BigDecimal.ZERO, BigDecimal::add) // sum sums

)

));

This will sum all the bd of Two, and then also sum the sums for Ones that have the same one.

Although things would be simpler if Java8 had a flatMapping collector, one has been added to Java9:

public static

Collector flatMapping(Function super T, ? extends Stream extends U>> mapper,

Collector super U, A, R> downstream) {

BiConsumer downstreamAccumulator = downstream.accumulator();

return Collector.of(downstream.supplier(),

(r, t) -> mapper.apply(t).sequential().forEach(u -> downstreamAccumulator.accept(r, u)),

downstream.combiner(),

downstream.finisher(),

downstream.characteristics().stream().toArray(Collector.Characteristics[]::new));

}

Which would make:

Map result1 = list.stream()

.collect(Collectors.groupingBy(One::getOne,

flatMapping(one -> one.getTwo().stream().map(Two::getBd),

Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)

)

));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值