设置唯一 = new HashSet(list);
和
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}
一个一个地编辑输出:迭代地图的条目集
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
编辑 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
请注意,您将始终拥有一个集合,并且您需要以一种或另一种方式从中提取特定单词的计数。