加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:25:20 所属栏目:Java 来源:网络整理
导读:我目前的尝试是基于双重类型的类成员: public Client whoPaidTheMost() {/*METHOD EXPLOITING STREAM API*/return shopping.entrySet() .stream() .collect(Collectors.groupingBy(Map.Entry::getKey,Collectors.flatMapping(e - e.getValue().entrySet().s

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

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俩.零是该总和的良好标识元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读