I am somewhat new to programming and struggle with this task. I have a table with names (strings) and corresponding values (int). Now I'm looking for duplicates in the names and add up the int values if the name already exists in the table.
I have a vague idea of how I could do this but I'm also pretty sure this is not the ideal solution to the problem. I'm trying to optimize the results that I am getting. My idea is using 2 Arrays, one for the names and one for the numbers, if there is a duplicate name in the Array, I'll go to the same position in the numbers Array and add the corresponding numbers. My initial idea looks like this:
String[] names = {a,b,a,a,c,b};
Integer[] numbers = {5,2,3,1,2,1};
for (int i = 0; i < names.length; i++) {
for (int j = i + 1; j < names.length; j++) {
if (names[i].equals(names[j]) ) {
numbers[i] += numbers[j]
} System.out.println("Name: " + names[i] + " Amount: " + numbers[i])
}
}
The intended output should be along the lines of this:
a = 10
b = 3
c = 1
I know this is a brute force method but I need to know the positions in the Array for this to work. I have no experience with treemaps but that might be an easier solution to the problem at hand. Thank you for your help.
I already suggested it in the comments: You can use a map to count all the values.
Here is an intentionally verbose example (to make clear what happens):
String[] names = {"a","b","a","a","c","b"};
Integer[] numbers = {5,2,3,1,2,1};
Map<String, Integer> totals = new HashMap<String, Integer>();
for (int i = 0; i < names.length; i++) {
if (totals.containsKey(names[i])) {
totals.put(names[i], totals.get(names[i]) + numbers[i]);
} else {
totals.put(names[i], numbers[i]);
}
}
System.out.println(totals);
So if the name is already in the map, just increase the count by the new number. If it's not, add a new map entry with the number.
Beware that for this to work, your two arrays must be of equal length!
This will print:
{a=9, b=3, c=2}