繁体   English   中英

在流API收集器中汇总BigDecimals

[英]Summing BigDecimals in streams API Collectors

我目前的尝试基于双类型成员:

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

  • 外键代表客户端
  • 内键代表产品
  • 内部映射值(整数)表示属于特定客户端的指定产品的数量

产品类成员是名称,类别,价格 (以前是双重类型) - 想要使用price作为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之前Collectors.mapping(e -> BigDecimal.valueOf(new Long(e.getValue())).multiply(e.getKey().getPrize())

如果您正在寻找一个总和BigDecimalCollector ,这应该工作:

Collector<BigDecimal, ?, BigDecimal> collector 
    = Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);

你可以像这样重构它,

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>传递下来。 最终的减少运算符在这里诀窍。 零作为此总和的良好身份元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM