Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap : Adding values with common keys and printing them out

I have file which has String in the form key/value pair like people and count, example would be

"Reggy, 15"
"Jenny, 20"
"Reggy, 4"
"Jenny, 5"

and in the output I should have summed up all count values based on key so for our example output would be

"Reggy, 19" "Jenny, 25"

Here is my approach:

  1. Read each line and for each line get key and count using scanner and having , as delimiter
  2. Now see if key is already present before if then just add currentValues to previousValues if not then take currentValue as value of HashMap.

Sample Implementation:

public static void main(final String[] argv) {
    final File file = new File("C:\\Users\\rachel\\Desktop\\keyCount.txt");

    try {
        final Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            if (scanner.hasNext(".*,")) {
                String key;
                final String value;

                key = scanner.next(".*,").trim();

                if (!(scanner.hasNext())) {
                    // pick a better exception to throw
                    throw new Error("Missing value for key: " + key);
                }

                key = key.substring(0, key.length() - 1);
                value = scanner.next();

                System.out.println("key = " + key + " value = " + value);
            }
        }
    } catch (final FileNotFoundException ex) {
        ex.printStackTrace();
    }
}

Part I am not clear about is how to divide key/value pair while reading them in and creating HashMap based on that.

Also is the approach am suggestion an optimal one or is there a way to enhance the performance more.

like image 450
Rachel Avatar asked Dec 08 '22 17:12

Rachel


2 Answers

Since this is almost certainly a learning exercise, I'll stay away from writing code, letting you have all the fun.

Create a HashMap<String,Integer>. Every time that you see a key/value pair, check if the hash map has a value for the key (use 'containsKey(key)'). If it does, get that old value using get(key), add the new value, and store the result back using put(key, newValue). If the key is not there yet, add a new one - again, using put. Don't forget to make an int out if the String value (use Integer.valueOf(value) for that).

As far as optimizing goes, any optimization at this point would be premature: it does not even work! However, it's hard to get much faster than a single loop that you have, which is also rather straightforward.

like image 110
Sergey Kalinichenko Avatar answered Dec 11 '22 11:12

Sergey Kalinichenko


Try this:

Map<String, Long> map = new HashMap<String, Long>();

while (scanner.hasNextLine()) {
        if (scanner.hasNext(".*,")) {
            ....
            if(map.containsKey(key))
                map.put(key, map.get(key) + Long.valueOf(value));
            else
                map.put(key, Long.valueOf(value));
        }
    }
like image 41
ogzd Avatar answered Dec 11 '22 10:12

ogzd