I am writing a Java string formatter and I think I am making it more complicated than it is maybe? I have a file that gives a list a stores:
"100|Pete's Pizza Palace|George Smith|200"
"400|Pete's Pizza Palace|George Smith|30"
"320|Pete's Pizza Palace|George Smith|-13"
"310|Pete's Pizza Palace|John Smith|2"
The output should look: "Pete's Pizza Palace|George Smith|217,Pete's Pizza Palaca|John Smith|2"
So, there's the storenumber removed in the first section then the added profits for the same stores. I do not seem to put in the map to get the sum for the same key string.
static String fileRecords(String[] records) {
int len = records.length;
Map<String, Integer> map = new HashMap<String, Integer>();
Map<String, Integer> profitTotals = new HashMap<String, Integer>();
String[] record = new String[len];
int index = 0;
int[] sums = new int[len];
StringBuilder sb = new StringBuilder();
StringBuilder tempStringBuilder = new StringBuilder();
int totalSum = 0;
for(int i = 0;i<len;i++) {
record = records[i].split("\\|");
String recEntryNameString = tempStringBuilder.append(record[1]).append("|").append(record[2]).append("|").toString();
map.put(recEntryNameString, Integer.parseInt(record[3]));
profitTotals.put(recEntryNameString, Integer.parseInt(record[3]));
Iterator iter = map.entrySet().iterator();
for (Map.Entry<String, Integer> entries : map.entrySet()) {
for(Map.Entry<String, Integer> sumNum : profitTotals.entrySet()) {
if(!entries.getKey().equals(sumNum.getKey())) {
totalSum = entries.getKey() + sumNum.getKey();
map.replace(recEntryNameString, entries.getKey(), totalSum);
profitTotals.remove(recEntryNameString);
}
}
}
}
Iterator<String, Integer> iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<String, Integer> entry = iter.next();
if(iter.hasNext()==true)
sb.append(entry.getKey()).append(entry.getValue()).append(",");
else
sb.append(entry.getKey()).append(entry.getValue());
}
return sb.toString();
}
I get outputs that are really close but the again looking for the correct format
Pete's Pizza Palace|George Smith|Pete's Pizza Palace|George Smith|Pete's Pizza Palace|George
Smith|87,Pete's Pizza Palace|George Smith|100,Pete's Pizza Palace|George Smith|Pete's Pizza
Palace|George Smith|123,