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

核能气质少年 提交于 2019-12-13 09:09:01

问题


Is there any way to set the accumulator to 0 after every time we use it and after that it still performs the same function? or How to calculate the overall value for each key in a Map like this : String, Hashmap String, Integer ? I am trying to be as clarifying as I can but I don't have a clue about that.

/*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)
}
}

回答1:


Your question is a bit unclear but, here is an example that calculates values for a key in hashmap. Let's assume we have

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

Where X, Y and Z are of type String and their values are of type Integer. The following code, stores the above structure and then calculate X,Y,Z for US and UK.

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

the output:

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


来源:https://stackoverflow.com/questions/33977545/how-to-calculate-a-value-for-each-key-of-a-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!