簡體   English   中英

將新字符串添加到hashmap java

[英]adding new strings to a hashmap java

我正在編寫一個程序來讀取日志文件,然后計算某些字符串的顯示次數。 我試圖手動輸入字符串作為關鍵字,但由於有這么多,我認為搜索日志文件會更好,當遇到“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的鍵來查看是否存在! 這違背了使用散列映射的目的O(n)在解決方案中查找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的靜態方法的類。

由於這是您的要求 -

it should create a new string from "ua, " to the end of the line

由於不清楚一行是否以“ua”或“ua”開頭,因此可能位於該行的中間。 這可能是它應該是這樣的 -

  while ((sCurrentLine = br.readLine()) != null) 
    {

        if( sCurrentLine.indexOf("ua, ") != -1 ){
             String str = sCurrentLine.substr("ua, ");
             if(dayCount.get(str) != null){
                  dayCount.put(str, dayCount(str) +1 );
              }else{
                  dayCount.put(str, 1 ); 
              }
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM