java中sum方法的使用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3687549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:30:07  来源:igfitidea点击:

how to use the sum method in java

java

提问by user442471

I am reading in a text file with four columns of data to a HashMap. I want to sum the value columns. Can I get an example on using the sum method?

我正在读取一个包含四列数据的文本文件到HashMap. 我想对值列求和。我可以获得使用 sum 方法的示例吗?

回答by BalusC

There is no such method like that. There's however the additive operator +which can be used on numeric primitives/types like intand Integer.

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

Assuming that you've a Map<String, Integer>, here's an example:

假设你有一个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.

See also:

也可以看看:



Update: I just wanted to add one other hint; your coreproblem might be that you've the numbers in flavor of Stringobjects (since you're parsing a text file) and the +of course won't sum them up, but just concatenate them. You'd like to convert each number from Stringto Integerfirst. This can be done with Integer#valueOf(). E.g.

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

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

This way you can do basic arithmetic with numbers as intended.

通过这种方式,您可以按预期对数字进行基本算术运算。

回答by Carlos

Based on your question, I made the assumption that you actually need to know how to merge three value columns into one value so you can put it into a map. Here's an example which converts value columns of any type into one string and then puts it into a map. It assumes the first column is the key column and makes no assumptions on their data types.

根据您的问题,我假设您实际上需要知道如何将三个值列合并为一个值,以便将其放入地图中。这是一个示例,它将任何类型的值列转换为一个字符串,然后将其放入映射中。它假设第一列是关键列,并且不对它们的数据类型做任何假设。

//These are values for each column. column1 to column4.
Object column1 = ...
Object column2 = ...
Object column3 = ...
Object column4 = ...

//This is the map you are reading the values into.
Map<Object, String> map = new HashMap<Object, String>();

StringBuilder sb = new StringBuilder();
sb.append(column2);
sb.append(column3);
sb.append(column4);

map.put(column1, sb.toString());