How to sum values from Java Hashmap

This question already has an answer here:

  • How to efficiently iterate over each entry in a 'Map'? 38 answers

  • If you need to add all the values in a Map , try this:

    float sum = 0.0f;
    for (float f : map.values()) {
        sum += f;
    }
    

    At the end, the sum variable will contain the answer. So yes, for traversing a Map 's values it's best to use a for loop.


    You can definitely do that using a for-loop . You can either use an entry set:

    for (Entry<String, Float> entry : map.entrySet()) {
        sum += entry.getValue();
    }
    

    or in this case just:

    for (float value : map.values()) {
        sum += value;
    }
    

    Float sum = 0f;
    for (Float val : map.values()){
        sum += val;
    }
    
    //sum now contains the sum!
    

    for循环对于预期的目的确实很好,但是你也可以使用while循环和迭代器......

    链接地址: http://www.djcxy.com/p/23962.html

    上一篇: 如何迭代含有数组列表的Hashmap

    下一篇: 如何从Java Hashmap中总结值