Search code examples
javahashtable

Summing values of Hashtable in Java


I'm trying to sum all the values in a dictionary in Java (helping my kid with homework, I never work in Java). Here's what I've tried:

    Hashtable<Int, Int> jim_dict = new Hashtable<Int, Int>();
    Hashtable<Int, Int> pam_dict = new Hashtable<Int, Int>();

    int totalJimVotes() {
        int sum = 0;

        (int value: jim_dict.values()) {
            sum += value;
        }

        return sum;
    }

    int totalPamVotes() {
        int sum = 0;

        (int value : pam_dict.values()) {
            sum += value;
        }

        return sum;
    }

What did I foul up syntax-wise? I found another answer on SO for summing float values, but the syntax for it doesn't seem to work.


Solution

  • Here is the Example of Sums.

    Use jim_dict.values() for sum of values.

    Use jim_dict.keySet() for sum of keys.

            Hashtable<Integer, Integer> jim_dict = new Hashtable<Integer, Integer>();
            jim_dict.put(1, 10);
            jim_dict.put(2, 20);
            System.out.println("Values Sum:" + jim_dict.values().stream().mapToInt(Integer::intValue).sum());
            System.out.println("Keys Sum:" + jim_dict.keySet().stream().mapToInt(Integer::intValue).sum());