Is there any method for counting the occurrence of each item on an array?
Lets say I have:
String[] array = {"name1","name2","name3","name4", "name5"};
Here the output will be:
name1 1
name2 1
name3 1
name4 1
name5 1
and if I have:
String[] array = {"name1","name1","name2","name2", "name2"};
The output would be:
name1 2
name2 3
The output here is just to demonstrate the expected result.
You could use a
MultiSetfrom Google Collections/Guava or aBagfrom Apache Commons.If you have a collection instead of an array, you can use
addAll()to add the entire contents to the above data structure, and then apply thecount()method to each value. ASortedMultiSetorSortedBagwould give you the items in a defined order.Google Collections actually has very convenient ways of going from arrays to a
SortedMultiset.