Add up all the values in a list<Integer> and put it into a Hashmap<String, Integer>.

Discussion in 'Plugin Development' started by xxNightlordx, May 8, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    xxNightlordx

    How do I do this? I tried a lot of ways without success :(. Can anyone help me?
     
  2. Offline

    xmarinusx

    I'm not exactly sure what you want, but let's give it a try:
    Code:java
    1.  
    2. for(Integer i : nameOfList)
    3. {
    4. hashmap.put("string", i);
    5. }
    6.  
     
  3. Offline

    Suraski

    Code:
    int c = 0;
    for(Integer I : list) {
        c = c + I;
    }
     
    hashmap.put(key, c);
     
  4. Offline

    xmarinusx

    Actually, this will only put 1 value to the hashmap. You are first looping trough the entire list and then you're putting the last value of that list into the hashmap.
     
  5. Offline

    Comphenix

    Not the last value - the total of all the entries in the list.

    In fact, what you're describing, is exactly what your code will do. It loops through the entries of the list, replacing the previously set value with the current entry, until the last entry in the list will be associated with "string".

    And yes, that's pretty wasteful. If you DO want that, it's better to simply look up the last entry in the list by index. But, since OP talked about adding up all the values, and since that results in a single value, it's natural to associate the sum with a single key like Suraski.
     
  6. Offline

    xmarinusx

    Comphenix
    Yea you're totally right. Now I understand the post:p. At first I didn't know what he meant with "add up all the values", now I do...
     
  7. Offline

    xxNightlordx

    Would this be right:
    Code:
    public static HashMap<Faction, HashMap<Player, Integer>> killCount = new HashMap<Faction, HashMap<Player, Integer>>();
     
        public static int getDeaths(Faction f){
           
            int count = 0;
           
            List<Player> list = new ArrayList<Player>(FactionCount.killCount.get(f).keySet());
           
            for(Player a : list){
                count = count + FactionCount.killCount.get(f).get(a);
            }
           
            return count;
        }
     
  8. Offline

    xmarinusx

    xxNightlordx
    Yea this would be right, btw you can easier do: count += FactionCount.killCount.get(f).get(a);
     
Thread Status:
Not open for further replies.

Share This Page