Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from an array in Java [duplicate]

I am trying to write a program which will generate a random ten integer array(integers between 1 and 6) and then I have to form another array with all duplicates removed. So {1,3,5,5,3,4,2,2,2,1} should return {1,3,5,4,2}. The problem is that I get an answer but the output array contains 0s in the places where the duplicates were and I do not know how to decrease the length of the temp array(if it is even possible). Here is my program.:

import java.util.*;
public class Lab9Tut12{
public static void main (String[]args){
    int [] numbers = new int[10];
    //int length = 10;
    int[] temp = new int[length];
    for(int i=0;i<10;i++){
        numbers [i] = (int)(Math.random()*6+1);
        System.out.print(numbers [i]);
        System.out.println();
    }
    for(int i=1;i<10;i++){
       if(numbers[i-1]!=numbers[i]){
         temp[i]= numbers[i];
         //length--;
       }
    }
    System.out.println(Arrays.toString(temp));
}

}

like image 749
Georgi Koemdzhiev Avatar asked Mar 12 '14 13:03

Georgi Koemdzhiev


2 Answers

A nice way to do this is to utilize a Set. That's a structure, that contains only unique values.

Set<Integer> set = new HashSet<Integer>();
int[] array = {1,1,2,2,2,3,3,4,5,6,8};

for (int num : array) {
    set.add(num);
}

System.out.println(set);

Outputs:

[1, 2, 3, 4, 5, 6, 8]

To convert the set to an array you can use set.toArray().

like image 112
Warlord Avatar answered Sep 22 '22 01:09

Warlord


Use Set instead. Put all the array values in a set and then convert back to array.

Set<Integer> numbersSet = new HashSet<>(Arrays.asList(numbers));

Integer[] uniqueNumbers = numbersSet.toArray(new Integer[0]);

Set will eliminate all you duplicates and you don't need to do anything for it. Just put the numbers there.

like image 26
Avi Avatar answered Sep 22 '22 01:09

Avi