检查文件中单词列表的最有效方法 [英] Most Efficient Way to Check File for List of Words

查看:101
本文介绍了检查文件中单词列表的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚完成一项家庭作业,希望我将所有Java关键字添加到HashSet中.然后读入一个.java文件,并计算任何关键字出现在.java文件中的次数.

I just had a homework assignment that wanted me to add all the Java keywords to a HashSet. Then read in a .java file, and count how many times any keyword appeared in the .java file.

我走的路线是: 创建了一个包含所有关键字的String []数组. 创建一个HashSet,并使用Collections.addAll将数组添加到HashSet中. 然后,当我遍历文本文件时,我将通过HashSet.contains(currentWordFromFile);

The route I took was: Created an String[] array that contained all the keywords. Created a HashSet, and used Collections.addAll to add the array to the HashSet. Then as I iterated through the text file I would check it by HashSet.contains(currentWordFromFile);

有人建议使用HashTable进行此操作.然后,我看到了一个使用TreeSet的类似示例.我只是好奇..推荐这样做的方法是什么?

Someone recommended using a HashTable to do this. Then I seen a similar example using a TreeSet. I was just curious.. what's the recommended way to do this?

(在此处完成代码: http://pastebin.com/GdDmCWj0 )

推荐答案

尝试使用Map<String, Integer>,其中String是单词,而Integer是出现该单词的次数.

Try a Map<String, Integer> where the String is the word and the Integer is the number of times the word has been seen.

这样做的好处之一是您不需要处理文件两次.

One benefit of this is that you do not need to process the file twice.

这篇关于检查文件中单词列表的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆