我手边有很多话。我需要做的是保存它们并计算每个不同的单词。原始数据可能包含一些重复的单词。首先,我想使用Set,然后我可以保证我只得到不同的wrods。但我怎么能算他们的时代?是否有人有任何“聪明”的想法?
答案 0 :(得分:3)
您可以使用Guava库中的MultiSet
。
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multiset.html
答案 1 :(得分:2)
您可以使用Map解决此问题。
String sample = " I have a problem here. I have a lot of words at hand. What I need to do is to save them and count every different word. The original data may contains duplicate words.Firstly, I want to use Set, then I can guarantee that I only get the different wrods. But how can I count their times? Is there someone having any clever idea?";
String[] array = sample.split("[\\s\\.,\\?]");
Map<String,Integer> statistic = new HashMap<String,Integer>();
for (String elem:array){
String trimElem = elem.trim();
Integer count = 0;
if(!"".equals(trimElem)){
if(statistic.containsKey(trimElem)){
count = statistic.get(trimElem);
}
count++;
statistic.put(trimElem,count);
}
}
答案 2 :(得分:1)
也许你可以在java中使用hash,它是HashMap(或HashSet?) 你可以散列每个单词,如果该单词已被散列,则将一个与之相关的值递增一,这就是想法。