java - 将新字符串添加到 hashmap java

标签 java hashmap indexof

我正在编写一个程序来读取日志文件,然后计算某些字符串显示的次数。我试图手动输入字符串作为关键字,但由于有这么多,我决定搜索日志文件会更好,当它遇到“ua,”时,它应该创建一个新字符串,从“ua,”到该行的末尾,将其添加到 HashMap 中,并增加该特定字符串的计数(我感兴趣的所有字符串都以“ua,”开头)。我似乎无法弄清楚如何将新字符串添加到 HashMap 中。这是我到目前为止所拥有的。

public class Logs
{

public static void main(String args[]) throws IOException 
{

 Map<String, Integer> dayCount = new HashMap<String, Integer>();
    for (String str : KeyWords)
    {
        dayCount.put(str, 0);
    }

    File path = new File("C:\\P4logs"); 
    for(File f: path.listFiles())
    { // this loops through all the files + directories

        if(f.isFile()) 
        { // checks if it is a file, not a directory.

    try (BufferedReader br = new BufferedReader(new FileReader(f.getAbsolutePath())))
    {


String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) 
{
    boolean found = false;

    for (String str : DayCount.keySet()) 
    {
        if (sCurrentLine.indexOf(str) != -1)
        {
            DayCount.put(str, DayCount.get(str) + 1);
            found = true;
            break;
        }
     }
     if (!found && sCurrentLine.indexOf("ua, ") != -1)
     {
        System.out.println("Found an unknown user action: " + sCurrentLine);
        DayCount.put(key, value)    //not sure what to put here
     }
    }
   }
 for(String str : KeyWords)
    {
         System.out.println(str + " = " + DayCount.get(str));

    }

    }
   }
}

最佳答案

您无需遍历 HashMap 的键来查看是否存在!这违背了使用 HashMap 的目的(在您的解决方案中查找 O(1)O(n) 没有冲突)。你应该只需要做这样的事情:

//If a key doesn't exist in a hashmap, `get(T)` returns null
if(DayCount.get(str) == null) {
    //We know this key doesn't exist, so let's create a new entry with 1 as the count
    DayCount.put(str, 1);
} else {
    //We know this key exists, so let's get the old count, increment it, and then update
    //the value
    int count = DayCount.get(str);
    DayCount.put(str, count + 1);
}

另一方面,请考虑遵循 Java 命名约定。变量应以小写字母开头(即 dayCountDayCount)。只有类应该以大写字母开头。按照你现在的方式,看起来 DayCount 是一个类,它有一个名为 put 的静态方法。

关于java - 将新字符串添加到 hashmap java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15367938/

相关文章:

c# - 多次获取数组的索引,然后将它们存储在数组中

java - 使用Java的ByteBuffer复制Python的struct.pack

java - Spark java代码在spark_core v2.2中运行但在spark_core v2.3中失败

java - java中数据结构的内部实现?

java - ExpandableListView Android 中的多个 Textview

javascript - 遇到 JavaScript Array.indexOf 的奇怪现象(在 Node.js 中)

java - android – 在有限的时间内显示一个按钮

java - 如何设置不可变字段

javascript - 需要帮助查找整数数组中的逻辑缺陷以查找 K 个不同对的对

javascript - 使用 JavaScript 的 IndexOf 在数组中查找数组