计算ArrayList中单词的出现次数

时间:2011-03-06 14:58:24

标签: java arraylist count

我有ArrayList个包含重复条目的字词。

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

我该怎么做?

4 个答案:

答案 0 :(得分:54)

如果你没有大字符串列表,最短的实现方法是使用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

答案 1 :(得分:12)

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

答案 2 :(得分:1)

这是一个测试驱动的课程,可以做你想要的。首先是测试:

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

现在上课:

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

答案 3 :(得分:0)

或者如果你懒得自己做(或者是一个优秀的工业程序员:p),请使用google guava中的Multiset

相关问题