微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java-在流API收集器中汇总BigDecimals

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

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<客户,Map<产品,整数&gt ;、
>外键代表客户
>内键代表产品
>内部地图值(整数)表示属于特定客户的指定产品的数量

产品类成员名称,类别,价格(以前是double类型)-要使用price作为BigDecimal类型将提供的代码重构为一个代码

我怎样才能使此代码也适用于BigDecimals-?

基本上,我已经重构了arlead:

  Client client = shopping.entrySet()
            .stream()
            .collect(Collectors.groupingBy(Map.Entry::getKey,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.reducing之前的Collectors.mapping(e-> BigDecimal.valueOf(new Long(e.getValue())).multiply(e.getKey().getPrize())) ?

最佳答案
您可以像这样重构它,

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()))),BigDecimal::add))))
    .entrySet().stream()
    .max(Map.Entry.comparingByValue()).get().getKey();

在这里不需要任何其他映射收集器.只需使用map运算符即可根据您的计算将Map.Entry转换为BigDecimal,并将该Stream< BigDecimal>传递给下.最终归约运算符在这里完成了the俩.零是该总和的良好标识元素.

原文地址:https://www.jb51.cc/java/532818.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐