如何创建包含所有特定对象总和的地图?

How to create a map with sum of all specific objects?

我有一个对象:

class Sample
{
    String currency;
    String amount;
}

我想要一个包含特定货币所有对象总和的输出映射。

示例-

指针。我一直在使用以下代码,但它没有按我预期的那样工作。您可以使用此代码作为参考:

Map<String, Double> finalResult = samples
        .stream()
        .collect(Collectors.toMap(
                Sample::getCurrency,
                e -> e.getAmount()
                      .stream()
                      .sum()));

您需要将 groupingBysummingDouble 一起使用,而不是 toMap:

Map<String, Double> finalResult = samples
        .stream()
        .collect(Collectors.groupingBy(
                Sample::getCurrency,
                Collectors.summingDouble(Sample::getAmount)
        ));

我认为 amount 是 Double 类型,您的示例不正确 (String amount;)

Map<String, Double> finalResult = samples.stream().collect(
    Collectors.groupingBy(
          (Sample::getCurrency),
          Collectors.summingDouble(
             sample -> { return Double.parseDouble(sample.getAmount()); 
})));

只是想提供以下替代方案以供将来考虑。我还假设您的意思是 double 的数量以及适当的吸气剂。只要包含 merge function,就可以使用 Collectors.toMap。看起来你的想法是正确的,但语法是错误的。

List<Sample> samples =
                List.of(new Sample("USD", 10), new Sample("USD", 30),
                        new Sample("INR", 40), new Sample("INR", 90),
                        new Sample("EUR", 20), new Sample("EUR", 50));

toMap 的第三个参数是 merge function 以正确处理重复项。在这种情况下,它计算遇到的每个键的值的总和。

Map<String, Double> result = samples.stream()
           .collect(Collectors.toMap(
                 Sample::getCurrency, Sample::getAmount, Double::sum));

result.entrySet().forEach(System.out::println);

打印

EUR=70.0
USD=40.0
INR=130.0

如果您确实希望 class 将金额存储为 String,您可以将 Sample::getAmount 替换为 sample->Double.valueOf(sample.getAmount()) 以将 String 转换为一个Double。但是由于您可能会在计算中重复使用这些值,因此最好在创建 class 个实例时以最常用的形式存储数量。