gpt4 book ai didi

Java Hashmap 实现

转载 作者:行者123 更新时间:2023-11-30 05:57:20 27 4
gpt4 key购买 nike

我想使用 HashMap 来计算文件中多个字符串出现的次数。我该怎么做呢?另外,我是否能够以类似的方式计算唯一字符串的数量?示例将非常感激。

最佳答案

作为示例,下面的程序将从文件中读取单词并计算遇到 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 的方式。

  1. 创建一个新的 HashMap,将其命名为 uniqueStrings
  2. 从文件中读取字符串时,检查记录计数的 HashMap 是否包含当前字符串
    • 如果没有,则将其添加到 uniqueStrings
    • 如果存在,则将其从 uniqueStrings 中删除
  3. 读取完文件后,uniqueStrings 中将只有唯一的字符串

如果您有疑问,请告诉我。

希望这会有所帮助。
赫里斯托

关于Java Hashmap 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5846135/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com