Count occurrences of words in ArrayList
Here's a test-driven class that will do what you want. First the test:
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"));
}
}
Now the 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);
}
}
To solve your specific problem, you would create a counter, and iterate over your list, counting each element.
Counter<String> counter = new Counter<String>();
for (String string: myList)
counter.count(string);
There are lots of possibilities. A fast to implement solution could be to use a Map<String, Integer>
where the String is each individual word and Integer the count of each.
Traverse the list and increase the corresponding value in the map for it. In case there is no entry yet, add one with the value 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);
}
If you don't have a huge list of strings the shortest way to implement it is by using Collections.frequency
method, like this:
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));
}
Output:
aaa: 2
bbb: 1