HashMap:使用公共密钥添加值并将其打印出来

Rac*_*hel 4 java algorithm data-structures

我有文件,其形式key/value对中的字符串像人和计数,例如

"Reggy, 15"
"Jenny, 20"
"Reggy, 4"
"Jenny, 5"
Run Code Online (Sandbox Code Playgroud)

在输出中我应该根据键总结所有计数值,因此对于我们的示例输出将是

"Reggy,19""珍妮,25岁"

这是我的方法:

  1. 读取每一行,每行获取密钥并使用扫描仪计数并具有,分隔符
  2. 现在看,如果关键是已经存在之前,如果然后只需添加currentValues到previousValues如果没有的话拿CurrentValue的作为HashMap中的价值.

示例实施:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

第一部分我不清楚如何在读取它们时划分键/值对并根据它创建HashMap.

我也建议采用最佳方法,或者有更好的方法来提高性能.

das*_*ght 8

由于这几乎肯定是一个学习练习,我将远离编写代码,让你享受所有的乐趣.

创建一个HashMap<String,Integer>.每次看到键/值对时,检查哈希映射是否具有键的值(使用'containsKey(key)').如果是,则使用旧值get(key),添加新值,并使用返回结果存储put(key, newValue).如果密钥尚未存在,请添加一个新密钥 - 再次使用put.不要忘记int如果String value(Integer.valueOf(value)用于那个).

就优化而言,此时的任何优化都为时过早:它甚至都不起作用!但是,很难比单循环快得多,这也很简单.