Take the 2-minute tour ×

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) {

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.

share|improve this question
did you try java.util.HashMap#containsKey(),put(),get() ? –  ogzd Feb 8 '13 at 22:14
It's "pseudocode" :-) en.wikipedia.org/wiki/Pseudocode –  dnault Feb 8 '13 at 22:14
add comment

4 Answers

up vote 5 down vote accepted

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.

share|improve this answer
I am aware about that part of implementation but issue am having is while reading key/value pair data in. –  Rachel Feb 8 '13 at 22:23
@Rachel This should be really straightforward if you use Scanner to read lines, and then use split Take a look at this sample on ideone for a demo. –  dasblinkenlight Feb 8 '13 at 22:41
thanks, i got it now. –  Rachel Feb 8 '13 at 23:00
add comment

Simplest way I can think about splitting the values:

    Map<String, Integer> mapping = new HashMap<String,Integer>();

    String currentLine;

        String[] pair  = currentLine.split(",");

         if(pair.length != 2){ //could be less strict
            throw new DataFormatException();

         key = pair[0];
         value = Integer.parseInt(pair[1]);
             value +=  map.get(key);

It is most likely not the most efficient way in terms of performance, but is pretty straightforward. Scanner is usually used for parsing, but the parsing here doesn't look as complex, is just a split of strings.

share|improve this answer
add comment

For reading in, personally, I'd use:

Scanner.nextLine(), String.split(","), and Integer.valueOf(value)

share|improve this answer
this should be a comment –  mre Feb 8 '13 at 22:18
Should be split(",") since it expects a String. –  Sednus Feb 8 '13 at 22:21
add comment

Try this:

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

while (scanner.hasNextLine()) {
        if (scanner.hasNext(".*,")) {
                map.put(key, map.get(key) + Long.valueOf(value));
                map.put(key, Long.valueOf(value));
share|improve this answer
Why Long, certainly the numbers look like age. shouldn't be worried about exceeding Integer's values –  Sednus Feb 8 '13 at 22:23
look like age? Then these two Reggie and Jenny are not the same person :-) which is a completely different case. Besides looks like is not a good argument. –  ogzd Feb 8 '13 at 22:25
That's true, however, should be picked judiciously. –  Sednus Feb 8 '13 at 22:28
add comment

Your Answer


