my dog learned polymorphism
The moose likes Java in General and the fly likes Remove duplicates from Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Remove duplicates from Collection" Watch "Remove duplicates from Collection" New topic
Author

Remove duplicates from Collection

Charu Ak
Greenhorn

Joined: Aug 17, 2006
Posts: 15
Hi All,
I get a result set from database in the form of Collection which contains few objects of a particular class type. This class implements serializable and comparable implementing compareTo() and overriding equals and hashcode.

The task is to remove duplicate objects (by duplicate i mean with same values) from collection.

One possible approach i can think here is to convert this collection into a Set. But I am not sure how Set removes duplicates and I cannot really check my code as it runs on hub and can b deployed only after build.

Any help/direction is appreciated.

Thanks
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
Converting your Collection into a set is the easiest approach.

The Set implementation follows the hashCode & equals contract to determine meaningfully equivalent objects.

So if hashCode and equals are properly overridden, a set does fine.


JDBCSupport - An easy to use, light-weight JDBC framework -
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Remove duplicates from Collection
 
Similar Threads
Collection question
Question about HashSet
Comparators
methods, instances and arrays - swimming in the ocean of java
duplicate/unique value count generics list