如何在java中使用sum方法

use*_*471 0 java

我正在阅读一个包含四列数据的文本文件HashMap.我想总结值列.我可以得到一个使用sum方法的例子吗?

Bal*_*usC 6

没有这样的方法.然而,添加运算符+可用于数字基元/类型intInteger.

假设你有一个Map<String, Integer>,这是一个例子:

int total = 0;
for (Integer value : map.values()) {
    total = total + value; // Can also be done by total += value;
}
System.out.println(total); // Should print the total.
Run Code Online (Sandbox Code Playgroud)

也可以看看:


更新:我只想添加另一个提示; 你的核心问题可能是你拥有String对象风格的数字(因为你正在解析一个文本文件)+,当然不会总结它们,而只是将它们连接起来.您想将每个号码转换StringInteger第一个号码.这可以通过以下方式完成Integer#valueOf().例如

String numberAsString = "10";
Integer numberAsInteger = Integer.valueOf(numberAsString);
// Now put in map and so on.
Run Code Online (Sandbox Code Playgroud)

这样您就可以按照预期对数字进行基本算术运算.