How to Count Matched Elements in ArrayList in Java
i have question about how to count matched 开发者_开发百科elements in ArrayList in java.. Ex: My ArrayList contain [sport, sport, ball , player, sport]
i need to output like:
word sport frequency 3
word ball frequency 1
word player frequency 1
thanks for advance
Use a Map:
Map<String, Integer> occurrencies = new HashMap<String, Integer>();
for (String word : list) {
occurrencies.put(word, occurrencies.containsKey(word)
? occurrencies.get(word) + 1 : 1);
}
for (Entry<String, Integer> entry : occurrencies.entrySet()) {
System.out.println("Word: "+entry.getKey()
+ ", occurences: "+entry.getValue());
}
If you want the words to be sorted alphabetically, use TreeMap
instead of HashMap
.
(Of course this would be much easier using a Guava Multiset
as others have suggested)
If you're willing to pull in an external dependency: The Google Guava libraries contain various implementations of a Multiset, which is the name for the thing you want. If you're not willing to depend on a library for this you could at least look at the source code. A Multiset is basically a Map of some type to an integer which holds the count of the particular item in the collection.
Of course I'm assuming that you're actually able to replace your ArrayList with a Multiset.
Copy the content into another datastructure:
Map<String, Integer>
The key (String
) is the word, the Integer
value stores the count.
you can also sort the list and then count how many times a word is repeated
added bonus of alphabetic order in output
精彩评论