title: HashMap : Adding values with common keys and printing them out
body: <p>I have file which has String in the form <code>key/value</code> pair like people and count, example would be </p>
  
  <pre><code>"Reggy, 15"
  "Jenny, 20"
  "Reggy, 4"
  "Jenny, 5"
  </code></pre>
  
  <p>and in the output I should have summed up all count values based on key so for our example output would be </p>
  
  <p>"Reggy, 19"
  "Jenny, 25"</p>
  
  <p>Here is my approach:</p>
  
  <ol>
  <li>Read each line and for each line get key and count using scanner and having <code>,</code> as delimiter </li>
  <li>Now see if key is already present before if then just add currentValues to previousValues if not then take currentValue as value of HashMap. </li>
  </ol>
  
  <p>Sample Implementation:</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>Part I am not clear about is how to divide key/value pair while reading them in and creating HashMap based on that. </p>
  
  <p>Also is the approach am suggestion an optimal one or is there a way to enhance the performance more. </p>