计数ArrayList中单词的出现次数

我有一个具有重复条目的单词ArrayList

我想计算并保存数据结构中每个单词的出现次数。

我该怎么做?

如果你没有大的string列表,最简单的方法是使用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 

有很多的可能性。 一个快速实现的解决scheme可以使用一个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); } 

这是一个testing驱动的类,将会做你想做的。 首先testing:

 import 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")); } } 

现在这个class级:

 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); } } 

为了解决您的具体问题,您可以创build一个计数器,并遍历您的列表,计算每个元素。

 Counter<String> counter = new Counter<String>(); for (String string: myList) counter.count(string); 

或者如果你懒得自己做(或者一个好的工业程序员:p),可以使用谷歌guava的Multiset。