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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With