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:
,
as delimiter 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.
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.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With