简体   繁体   English

Java Hashmap 实现

[英]Java Hashmap implementation

I want to use a hashmap to count the number of occurrences of several strings in a file.我想使用 hashmap 来计算文件中几个字符串的出现次数。 How would I go about doing this?我将如何 go 这样做? Also, would I be able to count the number of unique strings in a similar fashion?另外,我能否以类似的方式计算唯一字符串的数量? Examples would be much appreciated.例子将不胜感激。

As an example, here's a program that will read words from a file and count how many times a Java keyword was encountered.例如,这是一个程序,它将从文件中读取单词并计算遇到 Java 关键字的次数。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

public class CountKeywords {

    public static void main(String args[]) {

        String[] theKeywords = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" };

        // put each keyword in the map with value 0 
        Map<String, Integer> theKeywordCount = new HashMap<String, Integer>();
        for (String str : theKeywords) {
            theKeywordCount.put(str, 0);
        }

        FileReader fr;
        BufferedReader br;
        File file = new File(args[0]); // the filename is passed in as a String

        // attempt to open and read file
        try {
            fr = new FileReader(file);
            br = new BufferedReader(fr);

            String sLine;

            // read lines until reaching the end of the file
            while ((sLine = br.readLine()) != null) {

                // if an empty line was read
                if (sLine.length() != 0) {

                    // extract the words from the current line in the file
                    if (theKeywordCount.containsKey(sLine)) {
                        theKeywordCount.put(sLine, theKeywordCount.get(sLine) + 1);
                    }
                }
            }

        } catch (FileNotFoundException exception) {
            // Unable to find file.
            exception.printStackTrace();
        } catch (IOException exception) {
            // Unable to read line.
            exception.printStackTrace();
        } finally {
                br.close();
            }

        // count how many times each keyword was encontered
        int occurrences = 0;
        for (Integer i : theKeywordCount.values()) {
            occurrences += i;
        }

        System.out.println("\n\nTotal occurences in file: " + occurrences);
    }
}

To answer your question about unique strings, you can adapt the way I use the HashMap in a similar fashion.要回答有关唯一字符串的问题,您可以调整我以类似方式使用 HashMap 的方式。

  1. create a new HashMap, call it uniqueStrings创建一个新的 HashMap,称之为uniqueStrings
  2. when reading strings from the file, check if the HashMap that keeps track of the count contains the current string从文件中读取字符串时,检查跟踪计数的 HashMap 是否包含当前字符串
    • if it doesn't, then add it to uniqueStrings如果没有,则将其添加到uniqueStrings
    • if it does, then remove it from uniqueStrings如果是,则将其从uniqueStrings中删除
  3. after you're done reading the file, you will have only unique strings in uniqueStrings阅读完文件后,您将在uniqueStrings中只有唯一字符串

Let me know if you have questions.如果您有任何问题,请告诉我。

I hope this helps.我希望这有帮助。
Hristo赫里斯托

For tracking unique strings, you don't need to keep track of the number of occurrences in the file.要跟踪唯一字符串,您不需要跟踪文件中出现的次数。 Rather, you can use a HashSet instead of a HashMap for code clarity.相反,为了代码清晰,您可以使用HashSet而不是HashMap

Note: HashSet is internally backed by a HashMap with a final object used as the Value in the Key Value pair.注意: HashSet在内部由HashMap支持,最终 object 用作键值对中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM