Two Laptop Bag
The moose likes Java in General and the fly likes Finding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Finding "equal" elements in a List." Watch "Finding "equal" elements in a List." New topic

Finding "equal" elements in a List.

Landon Blake
Ranch Hand

Joined: Oct 15, 2004
Posts: 44
What is the easiest way to find elements with the same Value in a List? Is there a utility class that allows you to determine if a list contains duplicate "values"? How about the number of duplicate values?


Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33130

The easiest thing I can think of is to put all the objects in a HashSet and then compare the number of elements in the set to the number of elements in a list. The set takes care of filtering duplicates. And the difference in size would be the number of duplicates.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Alternately, if you want to know the number of duplicates for each element, you can use something like the MultiCounter I posted here. You could add methods to do things like find the most common element, or give a Set of all the keys.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Finding "equal" elements in a List.
It's not a secret anymore!