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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...