Java Program To Find Unique Elements In An Array
Chapter:
Miscellaneous
Last Updated:
14-05-2023 12:00:10 UTC
Program:
/* ............... START ............... */
import java.util.ArrayList;
import java.util.HashSet;
public class UniqueElementsFinder {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 2, 3, 5, 6, 1};
int[] uniqueElements = findUniqueElements(array);
System.out.println("Unique elements in the array: ");
for (int element : uniqueElements) {
System.out.print(element + " ");
}
}
public static int[] findUniqueElements(int[] array) {
HashSet<Integer> uniqueSet = new HashSet<>();
ArrayList<Integer> uniqueList = new ArrayList<>();
for (int element : array) {
if (!uniqueSet.contains(element)) {
uniqueSet.add(element);
uniqueList.add(element);
}
}
int[] uniqueArray = new int[uniqueList.size()];
for (int i = 0; i < uniqueList.size(); i++) {
uniqueArray[i] = uniqueList.get(i);
}
return uniqueArray;
}
}
/* ............... END ............... */
Output
Unique elements in the array:
1 2 3 4 5 6
The program finds the unique elements in the given array {1, 2, 3, 4, 2, 3, 5, 6, 1} and prints
them in the order they appear. The unique elements in this case are 1, 2, 3, 4, 5, and 6.
Notes:
-
In this program, the findUniqueElements method takes an array as input and uses a HashSet and an ArrayList to find and store the unique elements. The HashSet is used to check if an element has already been encountered, and the ArrayList is used to maintain the order of the unique elements.
- The findUniqueElements method returns an array containing the unique elements found. The main method demonstrates the usage of this method by creating an array, calling findUniqueElements, and printing the unique elements.
- In summary, the program utilizes a HashSet to keep track of unique elements and an ArrayList to maintain the order of those elements. By iterating over the input array and checking for duplicates, the program creates a new array containing only the unique elements, which are then printed as the output.