我有一个包含重复词条的ArrayList
。
我想要对每个单词进行计数并将其存储在数据结构中。
我该如何实现?
如果您没有一个巨大的字符串列表,实现它的最短方式是使用Collections.frequency
方法,像这样:
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) {
System.out.println(key + ": " + Collections.frequency(list, key));
}
输出:
aaa: 2
bbb: 1
有很多可能性。一个快速实现的解决方案是使用一个Map<String,Integer>
,其中String是每个单词,Integer是每个单词的计数。
遍历列表并增加该单词在地图中对应的值。如果还没有条目,则添加一个值为1的条目。
wordList = ....;
Map<String, Integer> wordCount = new HashMap<String, Integer>();
for(String word: wordList) {
Integer count = wordCount.get(word);
wordCount.put(word, (count==null) ? 1 : count+1);
}
Integer
是不可变的,你需要将它放回去:wordCount.put(word, wordCount.get(word)++) - 好的,我刚刚看到你已经修复了 :) - Yanick Rochonimport junit.framework.TestCase;
public class CounterTest extends TestCase {
private Counter<String> counter;
@Override
protected void setUp() throws Exception {
super.setUp();
counter = new Counter<String>();
}
public void testInitialCountIsZero() throws Exception {
assertEquals(0, counter.get("a"));
}
public void testCount() throws Exception {
counter.count("a");
assertEquals(1, counter.get("a"));
}
}
现在是类:
import java.util.HashMap;
public class Counter<T> {
private final HashMap<T, Integer> map = new HashMap<T, Integer>();
public int get(T key) {
final Integer n = map.get(key);
return n == null ? 0 : n;
}
public void count(T key) {
map.put(key, get(key) + 1);
}
}
Counter<String> counter = new Counter<String>();
for (String string: myList)
counter.count(string);