I have a file that has a String in the form of key/value , like people and a counter, for example,
"Reggy, 15" "Jenny, 20" "Reggy, 4" "Jenny, 5"
and in the output I had to sum all the account values based on the key, so for our example the output would be
Reggie 19 Jenny 25
Here is my approach:
- Read each line and for each line enter the key and count with a scanner and
, as a separator - Now let's see if the key is already present, if then just add currentValues to the previous values, if not, then accept currentValue as the HashMap value.
Implementation Example:
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())) {
Partly, I don’t understand how to separate a key / value pair by reading them and creating based on HashMap.
Also, the proposed approach is optimal, or is there a way to increase productivity.
source share