Count occurrences of words in ArrayList [duplicate]

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

Leave a Comment