Java t
Let's consider a classic problem: finding the unique elements in an array. In this scenario, we want to
extract only the distinct elements from the given array.
Here's a unique way to solve this problem using Java:
java
Copy code
import java.util.*;
public class UniqueElements {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 8, 9, 10, 1 };
int[] uniqueArray = findUniqueElements(arr);
System.out.println("Original Array: " + Arrays.toString(arr));
System.out.println("Unique Elements: " + Arrays.toString(uniqueArray));
}
public static int[] findUniqueElements(int[] arr) {
Map<Integer, Integer> countMap = new LinkedHashMap<>();
// Count occurrences of each element in the array
for (int num : arr) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
// Extract only the unique elements
List<Integer> uniqueList = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() == 1) {
uniqueList.add(entry.getKey());
java t
}
}
// Convert the list to an array
int[] uniqueArray = new int[uniqueList.size()];
for (int i = 0; i < uniqueList.size(); i++) {
uniqueArray[i] = uniqueList.get(i);
}
return uniqueArray;
}
}
This solution uses a LinkedHashMap to keep track of the occurrences of each element in the array. It
then iterates over the count map and extracts only the elements with a count of 1 (i.e., unique
elements). Finally, it converts the list of unique elements back into an array.
This approach ensures the elements are maintained in the order they first appeared in the original
array and efficiently finds the unique elements without using additional data structures like sets.
Demo Day 1 Video:
Conclusion:
Unogeeks is the No.1 Training Institute for Java Training. Anyone Disagree? Please drop in a comment
You can check out our other latest blogs on Java Training here – Java Blogs
You can check out our Best in Class Java Training details here – Java Training
Follow & Connect with us:
———————————-
For Training inquiries:
Call/Whatsapp: +91 73960 33555
Mail us at: info@unogeeks.com
Our Website ➜ https://unogeeks.com
Follow us:
Instagram: https://www.instagram.com/unogeeks
Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute
Twitter: https://twitter.com/unogeeks