如何将与哈希图中重复出现的键关联的值相加

How can I sum the values associated with a reoccurring key in a hashmap(如何将与哈希图中重复出现的键关联的值相加)
本文介绍了如何将与哈希图中重复出现的键关联的值相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想在哈希图中添加相同键的值.例如:

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

应该变成:

   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() + "		");

                        list.add(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        //System.out.print(cell.getNumericCellValue() + "		");

                        value = (int) cell.getNumericCellValue();
                        list.add(cell.getNumericCellValue());
                        break;
                    case Cell.CELL_TYPE_STRING:
                        //System.out.print(cell.getStringCellValue() + "		");
                        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 工作表中提取数据.

Note: I have used Apache POI to extract the data from an Excel sheet.

代码输出如下:

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?

推荐答案

Put 会覆盖地图中的任何内容.

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);

这篇关于如何将与哈希图中重复出现的键关联的值相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)