This code snippet show you how to create an array of unique numbers from another array of numbers.
package org.kodejava.example.lang;
public class UniqueArray {
/**
* Return true if number num is appeared only once in the
* array num is unique.
*/
public static boolean isUnique(int[] array, int num) {
for (int i = 0; i < array.length; i++) {
if (array[i] == num) {
return false;
}
}
return true;
}
/**
* Convert the given array to an array with unique values
* without duplicates and returns it.
*/
public static int[] toUniqueArray(int[] array) {
int[] temp = new int[array.length];
for (int i = 0; i < temp.length; i++) {
temp[i] = -1; // in case u have value of 0 in the array
}
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (isUnique(temp, array[i]))
temp[counter++] = array[i];
}
int[] uniqueArray = new int[counter];
System.arraycopy(temp, 0, uniqueArray, 0, uniqueArray.length);
return uniqueArray;
}
/**
* Print given array
*/
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
int[] array = {1, 1, 2, 3, 4, 1, 4, 7, 9, 7};
printArray(array);
printArray(toUniqueArray(array));
}
}
For other example to create unique array check the following example How do I remove duplicate element from array?.
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019
Thank you very much brother 🙂
You are welcome 🙂