Re: How to count duplicate items in ArrayList?
Ook wrote:
Say I have ArrayList<String>. Is there a function that will count duplicate
occurences of a specific item? I can do it with just a few lines of code,
but is there already something that will do that?
It depends on what you mean by "duplicate occurrence." If
two String objects that are distinct but have identical content
count as "duplicates," you could build a HashSet<String> from
your given collection and then ask for its size. If you mean
"duplicates" as "references to the exact same instance," you
could do a similar thing with IdentityHashMap<String,Object>
(using any arbitrary value -- null, say -- for the "value").
Either way, subtract the size() of the resulting collection
from the size() of the original list to count the duplicates.
If the original ArrayList is short, the obvious nested-loop
solution is probably better. But that's O(N*N), so for longer
lists you'll want to use the heavier artillery.
Postscript: Now I'm starting to wonder what you mean by
"a specific item." Perhaps you just want to know how many
times the String "Rover" appears in the list, not the fact
that "Rover" appears twice and "Fido" three times, for three
duplicates altogether. As far as I know there's no built-in way
to do the search -- maybe there's something you could do with
set intersection and set difference, but that sounds like
overkill. Just iterate over the list and test each element
with equals() or == as appropriate, keeping a count of hits.
But if you're going to perform a lot of searches like this, it
may be time to take a step back and ask whether ArrayList is
the right data structure for the job: Maybe you need a Map or
perhaps a SortedSet instead.
--
Eric Sosman
esosman@acm-dot-org.invalid