我想使用hashmap来计算文件中多个字符串的出现次数。我该怎么做呢?另外,我能以类似的方式计算唯一字符串的数量吗?举例非常感谢。
答案 0 :(得分:6)
例如,这是一个程序,它将读取文件中的单词并计算遇到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);
}
}
要回答有关唯一字符串的问题,您可以采用类似的方式调整我使用HashMap的方式。
uniqueStrings
uniqueStrings
uniqueStrings
uniqueStrings
如果您有疑问,请告诉我。
我希望这会有所帮助 赫里斯托斯
答案 1 :(得分:0)
要跟踪唯一字符串,您无需跟踪文件中出现的次数。相反,您可以使用HashSet
代替HashMap
来提高代码清晰度。
注意:HashSet
由HashMap
内部支持,最终对象用作键值对中的值。