将新字符串添加到hashmap java
发布时间:2020-12-15 04:08:14 所属栏目:Java 来源:网络整理
导读:我正在编写一个程序来读取日志文件,然后计算某些字符串的显示次数.我试图手动输入字符串作为关键字,但由于有这么多,我认为搜索日志文件会更好,当遇到“ua”时,它应该创建一个从“ua”到该行的结尾,将其添加到hashmap,并增加该特定字符串的计数(我感兴趣的所
我正在编写一个程序来读取日志文件,然后计算某些字符串的显示次数.我试图手动输入字符串作为关键字,但由于有这么多,我认为搜索日志文件会更好,当遇到“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(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命名约定.变量应以小写字母开头(即dayCount与DayCount).只有类应以大写字母开头.你现在拥有它的方式,看起来像DayCount是一个带有一个名为put的静态方法的类. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |