如何在Java Hashmap中对值进行求和

时间:2017-01-24 01:06:32

标签: java arraylist hashmap

我正在阅读输入文件:

Tuesday 50.40000000000001
Friday 35.5
Wednesday 51.5
Friday 46.49999999999999
Thursday 47.89999999999999
Friday 42.60000000000001
Tuesday 48.900000000000006
Thursday 47.300000000000026
Thursday 50.90000000000001
Wednesday 52.1
Monday 52.50000000000001
Thursday 53.1
Tuesday 49.000000000000014
Monday 36.900000000000006
Wednesday 46.70000000000001
Thursday 51.30000000000002
Monday 49.99999999999998

我想过滤每一天并总结其所有值 - 即添加所有星期一值,然后是星期二等等。我怎么能用Java做到这一点。我尝试使用代码如下的hashmap,但我无法做到。我需要帮助。

 public static void main(String[] args) throws NumberFormatException, IOException
    {
     BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("weekly.txt")));
     String line;
        while ((line = br.readLine()) != null) {

            String splittedWord []= line.split("\\s+");
            String key = splittedWord[0];

            map.put(key, new ArrayList<Double>());

            for(int i=1;i<splittedWord.length;i++){
                double temp = Double.parseDouble(splittedWord[i]);      
                if(map.containsKey(key)){
                    map.get(key).add(temp); // adding keys and values to the encode hashmap O(n)
                }

            } 
        }
        System.out.println("The size of encodeMap is " + map.size());

         Iterator test = map.entrySet().iterator();
            while (test.hasNext()) {
                Map.Entry pair = (Map.Entry)test.next();
                System.out.println(pair.getKey() + " " + pair.getValue());

                test.remove(); // avoids a ConcurrentModificationException             
            }           
    }

1 个答案:

答案 0 :(得分:0)

除非您需要存储每天的所有值,否则请按以下步骤更改代码:

 private static HashMap<String, Double> map = new HashMap<String, Double>();

    if(!map.containsKey(key)) {
        map.put(key, temp);
    } else {
        map.put(key, map.get(key) + temp);
    }