Monday, April 7, 2008

JAVA@ Removing Duplicate Records from ArrayList

The following code removes the duplicate records from the ArrayList of Java.

//////////////////////////////////////

import java.util.ArrayList;

public class RemoveDuplicateArrayElement {
public static void main(String [] as)
{
// String [] temp={"sqqa","as","sa","sd","sa","fd","sa","sa","sa"};
ArrayList aryDuplicate=new ArrayList();

aryDuplicate.add(new String("sabah"));
aryDuplicate.add(new String("irfan"));
aryDuplicate.add(new String("waqas"));
aryDuplicate.add(new String("sabah"));
aryDuplicate.add(new String("sabah"));
aryDuplicate.add(new String("Ahmad"));
// for(int i=0;i
// {
// if(listContains(aryL,temp[i]))
// {
// // This is already in the List, Don't push it.
// //System.out.println("List already contains"+temp[i]);
// }
// else
// {
// aryL.add(new String(temp[i]));
// }
// }
// aryDuplicate1=aryDuplicate;//
//
// for(int j=0;j
// {
// //System.out.println(j+":"+(String)aryDuplicate1.get(j));
// }

aryDuplicate=RemoveDuplicates(aryDuplicate);
System.out.println(aryDuplicate.size());
for(int j=0;j
{
System.out.println(j+":"+(String)aryDuplicate.get(j));
}
//System.out.println("List contains = "+listContains(aryL,"sfa") );
}
/////////////////////////////////////

public static ArrayList RemoveDuplicates(ArrayList aryLst)
{
ArrayList noDuplicate=new ArrayList();
for(int i=0;i
{

if(listContains(noDuplicate,(String)aryLst.get(i)))
{
//This is already in the List, Don't push it.
// System.out.println((String)aryLst.get(i));
}
else
{
noDuplicate.add(new String((String)aryLst.get(i)));

}
}

return noDuplicate;
}
/////////////////////////
public static boolean listContains(ArrayList aryList, String str)
{
boolean result=false;

for(int i=0;i
{
// System.out.println((String)aryList.get(i));
if(str.equalsIgnoreCase((String)aryList.get(i)))
{
result= true;
break;
}
else
{
result= false;
}

}

return result;
}
///////////////////////////////////

public static boolean listContains(String[] aryList, String str)
{
boolean result=false;

for(int i=0;i
{
// System.out.println((String)aryList.get(i));
if(str.equalsIgnoreCase((String)aryList[i]))
{
result= true;
break;
}
else
{
result= false;
}

}

return result;
}


} // end class

No comments: