如何计算数组列表中单词的重复次数? [英] How to Count Repetition of Words in Array List?
问题描述
我有这些代码用于在 Array-List 中搜索出现,但我的问题是如何获得结果在整数类型的这个for循环的外面,因为我需要在外面,可能有另一种方法可以找到不使用 for 循环的情况你能帮帮我吗?谢谢...
I've these code for searching occurrence in Array-List but my problem is how I can get result out side of this for loop in integer type cause I need in out side , may be there is another way for finding occurrence with out using for loop can you help me ? thank you...
List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("aaa");
Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
int accurNO = Collections.frequency(list, key);
System.out.println(key + ": " accurNO);
}
推荐答案
Set unique = new HashSet(list);
Set unique = new HashSet(list);
和
Collections.frequency(list, key);
Collections.frequency(list, key);
开销太大.
这是我要怎么做
List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("aaa");
Map<String, Integer> countMap = new HashMap<>();
for (String word : list) {
Integer count = countMap.get(word);
if(count == null) {
count = 0;
}
countMap.put(word, (count.intValue()+1));
}
System.out.println(countMap.toString());
输出
{aaa=2, bbb=1}
EDIT 一一输出:遍历地图的条目集
EDIT output one by one: iterate over the set of entries of the map
for(Entry<String, Integer> entry : countMap.entrySet()) {
System.out.println("frequency of '" + entry.getKey() + "' is "
+ entry.getValue());
}
输出
frequency of 'aaa' is 2
frequency of 'bbb' is 1
EDIT 2 无需循环
String word = null;
Integer frequency = null;
word = "aaa";
frequency = countMap.get(word);
System.out.println("frequency of '" + word + "' is " +
(frequency == null ? 0 : frequency.intValue()));
word = "bbb";
frequency = countMap.get(word);
System.out.println("frequency of '" + word + "' is " +
(frequency == null ? 0 : frequency.intValue()));
word = "foo";
frequency = countMap.get(word);
System.out.println("frequency of '" + word + "' is " +
(frequency == null ? 0 : frequency.intValue()));
输出
frequency of 'aaa' is 2
frequency of 'bbb' is 1
frequency of 'foo' is 0
请注意,您将始终拥有一个集合,并且您需要以某种方式提取特定单词的计数.
Note that you will always have a collection and you need extract the count from it for a particular word one way or another.
这篇关于如何计算数组列表中单词的重复次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!