how to use the sum method in java
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开发者_JAVA技巧 example on using the sum method?
There is no such method like that. There's however the additive operator +
which can be used on numeric primitives/types like int
and Integer
.
Assuming that you've a Map<String, Integer>
, here's an example:
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:
- Java tutorial - operators
- Java tutorial - the Map interface
- Java tutorial - the for statement
Update: I just wanted to add one other hint; your core problem might be that you've the numbers in flavor of String
objects (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 String
to Integer
first. This can be done with Integer#valueOf()
. E.g.
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.
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());
精彩评论