我现在的尝试是基于双类型的类成员:
public Client whoPaidTheMost() {
/*METHOD EXPLOITING STREAM API*/
return shopping.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.flatMapping(e -> e.getValue().entrySet().stream(),
Collectors.summingDouble(e->e.getKey().getPrize() * e.getValue())))) /*should be refactored*/
.entrySet().stream()
.max(Comparator.comparingDouble(Map.Entry::getValue))/*should be refactored*/
.get()
.getKey();
}
购物基本上是一个地图:Map<Client, Map<Product,Integer>>
,
产品类成员的名称,类别,价格(以前的双类型) -想用价格作为一种BigDecimal的所提供的代码重构为一个
我怎么能做出这样的代码工作,也为BigDecimals的 - ?
基本上,我已经重构是arleady:
Client client = shopping.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.flatMapping(e -> e.getValue().entrySet().stream(),
Collectors.mapping(e -> BigDecimal.valueOf(new Long(e.getValue())).multiply(e.getKey().getPrize()),
Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)))))
.entrySet().stream()
.max((e1, e2) -> (e1.getValue().compareTo(e2.getValue())))
.get()
.getKey();
不过不知道是否有可能重构这个不使用:Collectors.mapping(e -> BigDecimal.valueOf(new Long(e.getValue())).multiply(e.getKey().getPrize())
之前Collectors.reducing
?
你可以重构它这样,
shopping.entrySet().stream()
.collect(
Collectors.groupingBy(Map.Entry::getKey,
Collectors.flatMapping(
e -> e.getValue().entrySet().stream()
.map(innerEntry -> innerEntry.getKey().getPrice()
.multiply(BigDecimal.valueOf(innerEntry.getValue()))),
Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))))
.entrySet().stream()
.max(Map.Entry.comparingByValue()).get().getKey();
你不需要任何额外mapping
Collector
这里。仅仅使用map
运营商的转换Map.Entry
成BigDecimal
基于你的计算,并传递Stream<BigDecimal>
下去。最终降低运营商的伎俩在这里。零充当这个和良好的单位元。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句