Tuesday, June 16, 2009

Removing duplicate entries in an array

Below is the java code written to remove duplicate items from an array

 

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class Simple {
public static void main(String args[]){
     String arrayAsStr="IndianHippy,IndianHippy1,IndianHippy2,IndianHippy1,IndianHippy2,IndianHippy3,IndianHippy";
     String str[]=arrayAsStr.split(",");
     Arrays.sort(str);
     HashSet hs=new HashSet();
     for(int i=0;i<str.length;i++)
     {
             hs.add(str[i]);
     }
     String arraystr1[]=(String[])hs.toArray(new String[hs.size()]);
     String updatedArrayAsStr="";
     for(int i=0;i<arraystr1.length;i++)
     {
         if(updatedArrayAsStr.equals(""))
             updatedArrayAsStr=arraystr1[i];
         else
             updatedArrayAsStr=updatedArrayAsStr+","+arraystr1[i];
     }
    System.out.println(updatedArrayAsStr);
}
}

No comments:

Post a Comment