14

I am Java beginner, I found a few topics regarding this theme, but none of them worked for me. I have an array like this:

int[] numbers = {1, 1, 2, 1, 3, 4, 5};

and I would need to get this output:

1, 2, 3, 4, 5

Every item from that array just once.

But how to get it?

b4hand
  • 9,550
  • 4
  • 44
  • 49
user984621
  • 46,344
  • 73
  • 224
  • 412
  • 1
    I vote up because they have shut down your previous attempt http://stackoverflow.com/questions/14656208/array-of-unique-elements for a false reason. It is really a question. Just your title is wrong. It asks for count whereas the body requests for the items. – Val Apr 01 '13 at 21:37

17 Answers17

13

The simpliest solution without writing your own algorithm:

Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);

Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.

Maxim Kolesnikov
  • 5,075
  • 6
  • 38
  • 68
8

You can use a Set<Integer> and save lot of time since it holds unique elements. If you aren't allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort.

I'll post the Set<Integer> code:

int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
    setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
    System.out.println(x);
}

Note that I prefer to use LinkedHashSet as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2} then the output will be 2, 1 and not 1, 2.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Thanks you for your answer Luiggi. This belongs to the basic exercises, so I believe using a something more beginner-like is required. However, I am trying to implement your sample, but getting this error: `Set cannot be resolved to a type. LinkedHashSet cannot be resolved to a type` Do I miss any library or something like that? Thank you – user984621 Apr 01 '13 at 23:30
  • @user984621 you need to import those classes from `java.util` package. Below the `package your.package;` sentence, add `import java.util.*;`. – Luiggi Mendoza Apr 02 '13 at 00:27
  • Do you know why you can't use instead of when writing sets? –  May 17 '16 at 17:33
  • @Chi-YoungJeffreyLii in Java, `int` is a primitive type and generics are supported for reference types (classes and interfaces) only. `Integer` is a class wrapper for the primitive `int` type. – Luiggi Mendoza May 17 '16 at 17:34
  • What's the rationale behind that I mean. It seems like using primitive data types would be easier for some computations. –  May 17 '16 at 17:46
  • @Chi-YoungJeffreyLii that's how the language is designed. If you're looking for more info, please post a new question about it. – Luiggi Mendoza May 17 '16 at 17:47
5

In Java 8:

    final int[] expected = { 1, 2, 3, 4, 5 };

    final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };

    final int[] distinct = Arrays.stream(numbers)
        .distinct()
        .toArray();

    Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);

    final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };

    final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
        .sorted()
        .distinct()
        .toArray();

    Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);
Jeff
  • 3,712
  • 2
  • 22
  • 24
  • 2
    Do you know if `Arrays.stream(x).distinct().sorted().toArray()` would perform better than `Arrays.stream(x).sorted().dictinct().toArray()`? ie. Presumably the former would have fewer entries to sort? – Matt Coubrough Dec 13 '14 at 22:58
  • For what it's worth using JMH on the code above: Benchmark Mode Samples Score Error Units distinctSorted thrpt 200 465730.014 ± 2127.406 ops/s sortedDistinct thrpt 200 467130.970 ± 6364.848 ops/s – Jeff Dec 15 '14 at 03:20
3
//Running total of distinct integers found
int distinctIntegers = 0;

for (int j = 0; j < array.length; j++)
{
    //Get the next integer to check
    int thisInt = array[j];

    //Check if we've seen it before (by checking all array indexes below j)
    boolean seenThisIntBefore = false;
    for (int i = 0; i < j; i++)
    {
        if (thisInt == array[i])
        {
            seenThisIntBefore = true;
        }
    }

    //If we have not seen the integer before, increment the running total of distinct integers
    if (!seenThisIntBefore)
    {
        distinctIntegers++;
    }
}
Icemanind
  • 47,519
  • 50
  • 171
  • 296
2

Below code will print unique integers have a look:

printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});


static void printUniqueInteger(int array[]){
    HashMap<Integer, String> map = new HashMap();

    for(int i = 0; i < array.length; i++){
        map.put(array[i], "test");
    }

    for(Integer key : map.keySet()){
        System.out.println(key);
    }
}
b4hand
  • 9,550
  • 4
  • 44
  • 49
user_CC
  • 4,686
  • 3
  • 20
  • 15
2

Simple Hashing will be far efficient and faster than any Java inbuilt function:

public class Main 
{
    static int HASH[];
    public static void main(String[] args) 
    {
        int[] numbers = {1, 1, 2, 1, 3, 4, 5};
        HASH=new int[100000];
        for(int i=0;i<numbers.length;i++)
        {
            if(HASH[numbers[i]]==0)
            {
                System.out.print(numbers[i]+",");
                HASH[numbers[i]]=1;
            }
        }

    }
}

Time Complexity: O(N), where N=numbers.length

DEMO

b4hand
  • 9,550
  • 4
  • 44
  • 49
Ritesh Kumar Gupta
  • 5,055
  • 7
  • 45
  • 71
2
public class Practice {
    public static void main(String[] args) {
        List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
        countUnique(list);
}

public static void countUnique(List<Integer> list){
    Collections.sort(list);
    Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
    System.out.println(uniqueNumbers.size());
}

}

1

In JAVA8, you can simply use

stream()

and

distinct()

to get unique elements.

intArray = Arrays.stream(intArray).distinct().toArray();
Daniyal Javaid
  • 1,426
  • 2
  • 18
  • 32
1

There is an easier way to get a distinct list:

Integer[] intArray = {1,2,3,0,0,2,4,0,2,5,2};
List<Integer> intList = Arrays.asList(intArray);          //To List
intList = new ArrayList<>(new LinkedHashSet<>(intList));  //Distinct
Collections.sort(intList);                                //Optional Sort
intArray = intList.toArray(new Integer[0]);               //Back to array

Outputs:

1 2 3 0 0 2 4 0 2 5 2   //Array
1 2 3 0 0 2 4 0 2 5 2   //List
1 2 3 0 4 5             //Distinct List
0 1 2 3 4 5             //Distinct Sorted List
0 1 2 3 4 5             //Distinct Sorted Array

See jDoodle Example

Pierre
  • 8,397
  • 4
  • 64
  • 80
0

You could do it like this:

    int[] numbers = {1, 1, 2, 1, 3, 4, 5};
    ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary

    for (int n = 0; n < numbers.length; n++){
        if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
            store.add(numbers[n]);
        }
    }
    numbers = new int[store.size()];
    for (int n = 0; n < store.size(); n++){
        numbers[n] = store.get(n);
    }

Integer and int can be (almost) used interchangeably. This piece of code takes your array "numbers" and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store); before numbers = new int[store.size()]

Justin
  • 24,288
  • 12
  • 92
  • 142
0

I don't know if you've solved your issue yet, but my code would be:

    int[] numbers = {1, 1, 2, 1, 3, 4, 5};
    int x = numbers.length;
    int[] unique = new int[x];
    int p = 0;
    for(int i = 0; i < x; i++)
    {
        int temp = numbers[i];
        int b = 0;
        for(int y = 0; y < x; y++)
        {
            if(unique[y] != temp)
            {
               b++;
            }
        }
        if(b == x)
        {
            unique[p] = temp;
            p++;
        }
    }
    for(int a = 0; a < p; a++)
    {
        System.out.print(unique[a]);
        if(a < p-1)
        {
            System.out.print(", ");
        }
    }
b4hand
  • 9,550
  • 4
  • 44
  • 49
0
String s1[]=  {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};

int c=0;

for(int i=0;i<s1.length;i++)
{
    for(int j=i+1;j<s1.length;j++)
    {
    if(s1[i]==(s1[j]) )
    {
        c++;
    }
    }
        if(c==0)
         {
            System.out.println(s1[i]);
         }
            else
             {
            c=0;
              } 
            }
         }
      }
0

To find out unique data:

public class Uniquedata 
 {
 public static void main(String[] args) 
  {
int c=0;

String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};

for(int i=0;i<s1.length;i++)
{
    for(int j=i+1;j<s1.length;j++)
    {
    if(s1[i]==(s1[j]) )
    {
        c++;
        s1[j]="";
    }}
        if(c==0)
        {
            System.out.println(s1[i]);
        }
            else
            {
                s1[i]="";
            c=0;    
            }
        }
    }
}
Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38
0

you can use

Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
SOFe
  • 7,867
  • 4
  • 33
  • 61
0

Here is my piece of code using counting sort (partially)

Output is a sorted array consiting of unique elements

    void findUniqueElementsInArray(int arr[]) {
    int[] count = new int[256];
    int outputArrayLength = 0;
    for (int i = 0; i < arr.length; i++) {
        if (count[arr[i]] < 1) {
            count[arr[i]] = count[arr[i]] + 1;
            outputArrayLength++;
        }
    }
    for (int i = 1; i < 256; i++) {
        count[i] = count[i] + count[i - 1];
    }
    int[] sortedArray = new int[outputArrayLength];
    for (int i = 0; i < arr.length; i++) {
        sortedArray[count[arr[i]] - 1] = arr[i];
    }
    for (int i = 0; i < sortedArray.length; i++) {
        System.out.println(sortedArray[i]);
    }
}

Reference - discovered this solution while trying to solve a problem from HackerEarth

ericdemo07
  • 461
  • 8
  • 16
0

If you are a Java programmer, I recommend you to use this. It will work.

public class DistinctElementsInArray {

//Print all distinct elements in a given array without any duplication

    public static void printDistinct(int arr[], int n) {

        // Pick all elements one by one
        for (int i = 0; i < n; i++) {

            // Check if the picked element is already existed
            int j;
            for (j = 0; j < i; j++)
                if (arr[i] == arr[j])
                    break;

            // If not printed earlier, then print it
            if (i == j)
                System.out.print(arr[i] + " ");
        }
    }

    public static void main(String[] args) {
        int array[] = { 4, 5, 9, 5, 4, 6, 6, 5, 4, 10, 6, 4, 5, 3, 8, 4, 8, 3 };
        // 4 - 5 5 - 4 9 - 1 6 - 3 10 - 1 3 - 2 8 - 2

        int arrayLength = array.length;
        printDistinct(array, arrayLength);

    }
}
keikai
  • 14,085
  • 9
  • 49
  • 68
-1
public class DistinctArray {


    public static void main(String[] args) {
     int num[]={1,2,5,4,1,2,3,5};
     for(int i =0;i<num.length;i++)
     {
         boolean isDistinct=false;
         for(int j=0;j<i;j++)
         {
             if(num[j]==num[i])
             {
                 isDistinct=true;
                 break;
             }
         }
         if(!isDistinct)
         {
             System.out.print(num[i]+" ");
         }
     }
    }

}
Ali Akbarpour
  • 958
  • 2
  • 18
  • 35