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 List implementations to solve this.
In Collections, List allows duplicate values and maintain the insertion order, whereas Set does not allow duplicates, doesn't maintain order.

To achieve this, We can do this in a number of ways.

List Implementation: for Avoiding Duplicates-



  •  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 override the Add method and hashcode method to achieve without duplicates and order

list.SetUniqueList method:-


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

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

Related article

1 comments so far

If you need the insertion order you can use java.util.LinkedHashSet.


EmoticonEmoticon