Saturday, April 9, 2011

remove duplicates from int array in java

Ok so now you have a int array that has duplicate integers in it and you wanna remove them and have only unique elements. This is how i will do it.

Step 1:- Copy all the int elements into a HashSet. Reason for doing this is that the HashSet only stores unique elements.

Step 2:- Create a int array of size = HashSet's size

Step 3:- Copy all the the HashSet elements into the newly created int array

static int [] remove_duplicates(int array[]){

HashSet<Integer> hs = new HashSet<Integer>();

for(int i =0 ; i < array.length ; i++){
hs.add(array[i]);
}

int new_array[] = new int[hs.size()];

Iterator<Integer> itr = hs.iterator();
int i =0;
while(itr.hasNext()){
new_array[i]=itr.next();
i++;
}

return new_array;
}

No comments:

Post a Comment