Friday, 15 July 2011

java - HashMap : Adding values with common keys and printing them out -



java - HashMap : Adding values with common keys and printing them out -

i have file has string in form key/value pair people , count, illustration

"reggy, 15" "jenny, 20" "reggy, 4" "jenny, 5"

and in output should have summed count values based on key our illustration output

"reggy, 19" "jenny, 25"

here approach:

read each line , each line key , count using scanner , having , delimiter now see if key nowadays before if add together currentvalues previousvalues if not take currentvalue value of hashmap.

sample implementation:

public static void main(final string[] argv) { final file file = new file("c:\\users\\rachel\\desktop\\keycount.txt"); seek { 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 improve exception throw throw new error("missing value key: " + key); } key = key.substring(0, key.length() - 1); value = scanner.next(); system.out.println("key = " + key + " value = " + value); } } } grab (final filenotfoundexception ex) { ex.printstacktrace(); } }

part not clear how split key/value pair while reading them in , creating hashmap based on that.

also approach suggestion optimal 1 or there way enhance performance more.

since learning exercise, i'll remain away writing code, letting have fun.

create hashmap<string,integer>. every time see key/value pair, check if hash map has value key (use 'containskey(key)'). if does, old value using get(key), add together new value, , store result using put(key, newvalue). if key not there yet, add together new 1 - again, using put. don't forget create int out if string value (use integer.valueof(value) that).

as far optimizing goes, optimization @ point premature: not work! however, it's hard much faster single loop have, rather straightforward.

java algorithm data-structures

No comments:

Post a Comment