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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/java/532818.html

猜你在找的Java相关文章