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?.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Thank you very much brother 🙂
You are welcome 🙂