如何为 HashMap 的每个键计算一个值?

How to calculate a value for each key of a HashMap?

有没有什么办法可以在每次使用后将累加器设置为0,然后它仍然执行相同的功能?或者如何像这样计算 Map 中每个键的总值:String、Hashmap String、Integer?我正在尽力澄清,但我对此一无所知。

/*EXAMPLE OF HASHMAP:  String e.g - UK ; America ; Africa , etc. String e.g - black , white, asian Integer e.g- 2008 , 103432 , 2391 // for every country the values are diff
*/
//one way to think of this is maybe with accumulator
// THIS IS AN EXAMPLE CODE WHICH DOES NOTHING.
int acc = 0 ;
for ( int i = 0 ; i < 20 ; i++ ) {
if ( i == 1 ) {
acc++;  }       // after acc ++  and it is 1, I want it to be again 0;
if ( i == 3 ) {
acc++;  }       // so that on this stage it will be 1
}

//Another alternative way may be:
Map<String,HashMap<String,Integer>> question = new HashMap<>();
int count = 0 ;
for(String regions : question.keySet())
{
for (String people : question.get(regions).keySet())
{
count = count + question.get(regions).get(people);  // and here it will count all the value but I want to count it for each region and then become to 0 again, so that I can have the overall value for each of the people(keys)
}
}

您的问题有点不清楚,但是,这里有一个计算散列图中键值的示例。假设我们有

US -> [X -> 55, Y -> 5 , Z -> 10, ...] as one object
UK -> [X -> 99, Y -> 1, Z -> 50, W-> 23, ...] as other object

其中X、Y、Z是String类型,值是Integer类型。以下代码存储上述结构,然后计算美国和英国的 X、Y、Z。

 //structure to store a map of key/value for a key
 Map<String, Map<String, Integer>> hashmap = new HashMap<String, Map<String, Integer>>(); 

   //key/value map
   Map<String, Integer> US = new HashMap<String, Integer>(); 
   US.put("X", 1200); 
   US.put("Y", 50); 
   US.put("Z", 25552); 
   //can add any number, doesn't have to be three

   Map<String, Integer> UK = new HashMap<String, Integer>(); 
   UK.put("X", 222); 
   UK.put("Y", 52); 
   UK.put("Z", 18);

   hashmap.put("USA", US); 
   hashmap.put("UK", UK);

   //loop through main keys (i.e. US, UK, Africa, etc.)         
   for (String key : hashmap.keySet()) {
       Map<String, Integer> temp = hashmap.get(key); 
        System.out.println("Calculating for " + key);
        Integer sum = 0; 
        //for each key i.e. UK loop through its properties
        for(String otherKey: temp.keySet()) {
            sum = sum + temp.get(otherKey); 
        }
      System.out.println("Sum for " + key + " is " + sum);
   }

输出:

Calculating for USA
Sum for USA is 26802
Calculating for UK
Sum for UK is 292