Eliminate duplicate List of User defined Instance entries
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Ashok_Dinasarapu
Posted On:   Monday, June 1, 2009 06:54 PM

I have a list of User defined Instance variables. I WOULD LIKE TO ELIMINATE DUPLICATES.Can any one help me!

List lst = getCitations();

lst.get(0) = InstanceX;
lst.get(1) = InstanceY;
lst.get(2) = InstanceX;
lst.get(3) = InstanceX;
lst.get(4) = InstanceZ;
lst.get(5) = InstanceP;


How can I remove duplicate values (I only need one InstanceX in the given list and all the remaining) for the above list!

Thanks,
Biofly

Re: Eliminate duplicate List of User defined Instance entries

Posted By:   Anonymous  
Posted On:   Monday, July 6, 2009 01:30 PM

Hi,
There are more than way to actually eliminate duplicates, please see if one of them suits you best.


1. Convert List to Set to eliminate duplicates




void OriginalMethod(List sourceList){

int length= sourceList.size();
Set newSet = null;
int count=0;
//Hopefully converting List to Set will remove the duplicates
for(;count newSet.add(sourceList.get(count));
}
//You can convert the set back to List if you want
}


Hopefully doing so will remove the duplicates,
however if it's a String you may want to make sure whether there is no trailing or leading spaces.
If its an object, you may have to override equals and Hashcode to make sure Objects are truly unequal


2. Use Good old school way to use a Search algorithm like (Linear/Binary) search to find the duplicates...Follow the motto Seek and Destroy :J




static public int search(int [] array, int target)
{
int high = array.length, low = -1, probe;
while (high - low > 1)
{
probe = (high + low) / 2;
if (array[probe] < target)
low = probe;
else
high = probe;
}
if (high == array.length || array[high] != target)
return -1;
else
return high;
}


Search for target and remove that from the array and then search again and continue to remove
the elements which mach 'target' from the array until you have removed them all.
This will remove duplicates of any value you have searched for but may not be a very productive thing to do.

For the search to work properly the list has to be sorted, thus simply scanning through the array increasing the array position
by 1 each time and comparing it with the previous value should allow you to detect duplicates.

Re: Eliminate duplicate List of User defined Instance entries

Posted By:   Tim_Frith  
Posted On:   Tuesday, June 2, 2009 02:41 AM

About | Sitemap | Contact