Add a new string to HashMap Java

I'm writing a program to read the log file and count the number of times some strings are displayed I tried to manually enter a string as a keyword, but because there are so many, I think it would be better to search the log file. When encountering "UA", it should create a string from "UA" to the end of the line, add it to HashMap, and increase the count of the specific string (all strings I am interested in start with "UA") I can't seem to figure out how to add a new string to HashMap This is what I have so far

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));

    }

    }
   }
}

}

Solution

You don't need to traverse the HashMap keys to see if they exist! This is contrary to the purpose of using hash mapping (finding o (1) in the solution without colliding with O (n)) You should only do such things:

//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);
}

Also note that consider following the Java Naming Convention Variables should start with lowercase letters (i.e. daycount and daycount) Only classes should start with an uppercase letter You now have it in a way that looks like daycount is a class with a static method called put

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>