我需要确定特定列表的频率计数。我的列表将如下所示
gun,bun
bun,gun,
pin,bin
bin,pin
stay,way.从上面的列表中,我需要如下输出
gun,bun 2
pin,bin 2
stay,way 1有什么建议请提出来。
发布于 2011-02-25 19:29:52
//this is data string
String str = "gun,bun,bun,gun,pin,bin bin,pin,stay,way";
// here we have created a map with String key and Integer values
Map<String, Integer> hm = new HashMap<String, Integer>();
//now we are iterating through each string by splitting data by "," so we'll get each string
for (String strTmp : str.split(",")) {
//checking if map already contains the entry then update the count
if (hm.containsKey(strTmp)) {
Integer val = hm.get(strTmp);
val = val + 1;
hm.put(strTmp, val);
} else {//else just add it
hm.put(strTmp, 1);
}
}
//printing the result
System.out.println(hm);发布于 2011-02-25 19:38:37
您还应该了解一下频率法,特别是Iterables频率法
发布于 2011-02-25 19:29:05
使用HashMap<String,Integer>,遍历单词列表并存储计数。有关如何使用HashMap,请参阅此处的文档:
http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html
https://stackoverflow.com/questions/5116630
复制相似问题