How do I create array of unique values from another array?

This code snippet show you how to create an array of unique numbers from another array of numbers.

package org.kodejava.lang;

import java.util.Arrays;

public class UniqueArray {
    /**
     * Return true if num appeared only once in the array.
     */
    public static boolean isUnique(int[] numbers, int num) {
        for (int number : numbers) {
            if (number == num) {
                return false;
            }
        }
        return true;
    }

    /**
     * Convert the given array to an array with unique values and
     * returns it.
     */
    public static int[] toUniqueArray(int[] numbers) {
        int[] temp = new int[numbers.length];
        // in case you have value of 0 in the array
        Arrays.fill(temp, -1);

        int counter = 0;
        for (int number : numbers) {
            if (isUnique(temp, number))
                temp[counter++] = number;
        }

        int[] uniqueArray = new int[counter];
        System.arraycopy(temp, 0, uniqueArray, 0, uniqueArray.length);
        return uniqueArray;
    }

    /**
     * Print given array
     */
    public static void printArray(int[] numbers) {
        for (int number : numbers) {
            System.out.print(number + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 4, 1, 4, 7, 9, 7};
        printArray(numbers);
        printArray(toUniqueArray(numbers));
    }
}

For other example to create unique array check the following example How do I remove duplicate element from array?.

Wayan

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.