在流API收藏家总结BigDecimals的

Ares02:

我现在的尝试是基于双类型的类成员:

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>>

  • 外键表示客户端
  • 内主要代表产品
  • 内的地图值(整数)reprents属于特定客户端指定的产品的数量

产品类成员的名称,类别,价格(以前的双类型) -想用价格作为一种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

拉温德拉Ranwala:

你可以重构它这样,

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.EntryBigDecimal基于你的计算,并传递Stream<BigDecimal>下去。最终降低运营商的伎俩在这里。零充当这个和良好的单位元。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章