我想在哈希表中添加相同鍵的值。例如:我如何總結與哈希映射中的重複鍵相關聯的值
ABC --> 123
DEF --> 456
ABC --> 123
XXX --> 111
XXX --> 222
應該變成:
ABC --> 246
DEF --> 456
XXX --> 333
下面的代碼我到目前爲止:
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();
}
}
}
注:我使用的Apache POI從Excel表中提取數據。
代碼輸出這樣的:
DEF --> 456
ABC --> 123
XXX --> 222
這一切正在做的是覆蓋掉投入HashMap的平等關鍵的最後一個單元格。
是否有任何方法來總結的價值,而不是寫他們?
在代碼中,這會去哪裏?我認爲這將工作,但是當我嘗試它時,另一個鍵打印出'{null = 0,ABC = 123,'等 – LethalUniwhale
它代替了你使用的地方放置... – Cheruvian
替換hm.put(鍵,價值); – Cheruvian