Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of words in ArrayList [duplicate]

I have an ArrayList of words with duplicate entries.

I want to count and save occurrences for each word in a data structure.

How can I do it?

like image 885
Francesco Nigro Avatar asked Mar 06 '11 14:03

Francesco Nigro


People also ask

How do you count words in an ArrayList?

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.


1 Answers

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
like image 124
lukastymo Avatar answered Sep 20 '22 17:09

lukastymo