Monday, December 19, 2011

How to Store unique objects to avoid the duplicates in java List?.

In real time scenarios, you encountered the cases having duplicate objects in a list.
To remove the duplicates, There are no java Collections implementations to solve this.
In Collections, List allows duplicate values and maintain the insertion order, where as Set does not allows duplicates,doesn't maintain order.

To achive this,We can do this in number of ways.


1. We can write our own set and list implementation by extending List implementation and Implementing Set interface
You can not consider implementing List as already Set is implementing. You can Consider for extending ArrayList as it is not final
For this you need to overide the Add method and hashcode method to achive without duplicates and order


apache common-collection API provided org.apache.commons.collections.list.SetUniqueList class to avoid duplicates in a list

You can use this class for the same functinality
Please leave a comment if you need more information on implementation



Note: Only a member of this blog may post a comment.