How can I sum the values associated with a reoccurring key in a hashmap
apache-poi, excel, hashmap, java, sum
Solution
Put overwrites whatever is in the map.
You need to get the current value in the map for the key (if it exists) and add it to the value you want to store.
if(hm.containsKey(key))
hm.put(key, value + hm.get(key));
else
hm.put(key, value);
Problem
I want to add the values of the same keys in a hashmap. For example: ``` ABC --> 123 DEF --> 456 ABC --> 123 XXX --> 111 XXX --> 222 ``` should become: ``` ABC --> 246 DEF --> 456 XXX --> 333 ``` Here's the code I have so far: ``` public class Reading { @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { //Create hashmap to store the the string and int in the excel sheet HashMap<String, Integer> hm = new HashMap<String, Integer>(); String key = null; int value = Integer.MIN_VALUE; // String chkeq; // this @SuppressWarnings("rawtypes") ArrayList list = new ArrayList(); // File path or EXCEL file FileInputStream fos = new FileInputStream( "/Users/SG/Desktop/tester.xls"); // Sheet is the individual sheet that the data is coming from, in this // case Sheet1 try { // Put the XLS file into HSSFWorkbook workbook = new HSSFWorkbook(fos); // Get first sheet from the project HSSFSheet sheet = workbook.getSheetAt(0); // Go through each row Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); // Go through each column in the rows Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: //System.out.print(cell.getBooleanCellValue() + "\t\t"); list.add(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: //System.out.print(cell.getNumericCellValue() + "\t\t"); value = (int) cell.getNumericCellValue(); list.add(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: //System.out.print(cell.getStringCellValue() + "\t\t"); key = cell.getStringCellValue(); //chkeq = cell.getStringCellValue(); /* for (int i = 0; cellIterator.hasNext(); i++) { if (chkeq == cellIterator.next().getStringCellValue()) { System.out.println("same" + cell.getStringCellValue()); } }*/ list.add(cell.getStringCellValue()); break; } if (key != null && value != Integer.MIN_VALUE) { hm.put(key, value); key = null; value = Integer.MIN_VALUE; } } //System.out.println(""); } for (String keys : hm.keySet()) System.out.println(keys + ":" + hm.get(keys)); fos.close(); // System.out.println(list); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` Note: I have used Apache POI to extract the data from an Excel sheet. The code outputs this: ``` DEF --> 456 ABC --> 123 XXX --> 222 ``` All this is doing is overwriting the last cell that was put into the hashmap with equal key. Is there any way to sum the values instead of writing over them?