1

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

1
  • Imagine you can only see one item in that arraylist at a time. Just imagine. How will you solve this problem? Commented May 30, 2011 at 14:55

4 Answers 4

5

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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.

4 Comments

+1 for the Guava Multiset, although I doubt that the OP is ready to use a Library as sophisticated as Guava yet
Why using an external library when Java has Map<K,V>?
@MarcoS: In general (use in a real application) Multiset has an API that's much better suited to this than the Map API. However, I'm in agreement that the OP probably doesn't need it for the simple task in their example (particularly if it's homework).
@Sean: Yes, I think you're right. The OP is probably much better off with your solution.
1

Copy the content into another datastructure:

Map<String, Integer>

The key (String) is the word, the Integer value stores the count.

Comments

1

you can also sort the list and then count how many times a word is repeated

added bonus of alphabetic order in output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.