Java Program To Remove Duplicate Elements In An Array Using For Loop
In Java, handling arrays is a fundamental skill, and one common task involves managing duplicate elements. Removing duplicates ensures data integrity and can optimize performance in various applications. In this article, you will learn how to efficiently remove duplicate elements from a Java array using for loops.
Problem Statement
Arrays often contain redundant data, where the same element appears multiple times. This can lead to incorrect calculations, wasted storage space, and inefficient processing. For instance, in a list of product IDs, having duplicates might skew inventory counts or lead to errors in order-processing systems. The challenge is to identify and eliminate these repeated elements, producing a new array containing only unique values.
Example
Consider an array of integers with several repeated numbers:
- Input Array:
[10, 20, 20, 30, 40, 10, 50] - Desired Output (Unique Elements):
[10, 20, 30, 40, 50]
The goal is to transform the input array into the desired output using for loops.
Background & Knowledge Prerequisites
To understand the solution presented, you should be familiar with:
- Basic Java syntax: Variables, data types, and method calls.
- Arrays in Java: How to declare, initialize, and access elements.
-
forloops in Java: Iterating over arrays and controlling loop flow.
Use Cases
Removing duplicate elements from an array is a common requirement across many programming domains:
- Data Deduplication: Cleaning datasets to ensure each record is unique, crucial in database management and data analysis.
- User Management: Ensuring unique usernames or email addresses in a registration system to prevent conflicts.
- Inventory Control: Maintaining an accurate count of distinct products in stock, avoiding over-counting due to duplicate entries.
- Search Query Optimization: Processing unique keywords from user inputs to provide more relevant search results without redundant computations.
- Sensor Data Processing: Filtering out identical readings from sensors to analyze only distinct events or measurements.
Solution Approaches
We will focus on an approach that leverages nested for loops and a temporary array to identify and store unique elements.
Approach 1: Using Nested For Loops with a Temporary Array
This approach involves iterating through the original array and, for each element, checking if it already exists in a new temporary array meant to hold unique elements. If the element is not found in the temporary array, it is added.
// Remove Duplicates from Array using For Loop
import java.util.Arrays; // Required for Arrays.toString()
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Declare and initialize the array with duplicate elements
int[] originalArray = {10, 20, 20, 30, 40, 10, 50, 60, 60, 70};
System.out.println("Original array: " + Arrays.toString(originalArray));
// Step 2: Create a temporary array to store unique elements
// Initialize with the same size as original, as max unique elements can be same as original
int[] tempArray = new int[originalArray.length];
int uniqueCount = 0; // Counter for unique elements found
// Step 3: Iterate through the original array
for (int i = 0; i < originalArray.length; i++) {
boolean isDuplicate = false; // Flag to check if current element is a duplicate
// Step 4: For each element, check if it already exists in the tempArray
// Iterate only up to 'uniqueCount' because beyond that, tempArray has default values (0 for int)
for (int j = 0; j < uniqueCount; j++) {
if (originalArray[i] == tempArray[j]) {
isDuplicate = true; // Element found, it's a duplicate
break; // No need to check further in tempArray
}
}
// Step 5: If the element is not a duplicate, add it to tempArray
if (!isDuplicate) {
tempArray[uniqueCount] = originalArray[i];
uniqueCount++; // Increment count of unique elements
}
}
// Step 6: Create a new array of exact size 'uniqueCount' to store the final unique elements
int[] uniqueArray = new int[uniqueCount];
for (int i = 0; i < uniqueCount; i++) {
uniqueArray[i] = tempArray[i]; // Copy elements from tempArray to uniqueArray
}
System.out.println("Array after removing duplicates: " + Arrays.toString(uniqueArray));
}
}
Sample Output:
Original array: [10, 20, 20, 30, 40, 10, 50, 60, 60, 70]
Array after removing duplicates: [10, 20, 30, 40, 50, 60, 70]
Stepwise Explanation:
- Initialization: An
originalArraywith duplicates is declared. AtempArrayof the same size is created to temporarily hold unique elements, anduniqueCountis initialized to0to track how many unique elements have been found. - Outer Loop (Iterating Original Array): The first
forloop iterates through each element of theoriginalArray. - Inner Loop (Checking for Duplicates): For each element from the
originalArray, a nestedforloop checks if this element (originalArray[i]) already exists in thetempArray. This check only needs to run up touniqueCountbecause only those indices contain unique elements identified so far. - Marking Duplicates: If
originalArray[i]is found intempArray, theisDuplicateflag is set totrue, and the inner loop breaks early because the element's status as a duplicate is confirmed. - Adding Unique Elements: If
isDuplicateremainsfalseafter the inner loop completes (meaning the element was not found intempArray), thenoriginalArray[i]is a unique element. It is added totempArrayat theuniqueCountindex, anduniqueCountis incremented. - Final Array Creation: After both loops complete,
tempArraycontains all unique elements followed by default values (zeros). A newuniqueArrayis created with the precise size ofuniqueCount, and the unique elements fromtempArrayare copied into it. This step ensures the final array doesn't contain any trailing default values or unused space.
Conclusion
Removing duplicate elements from an array is a common data manipulation task. While various methods exist, using nested for loops with a temporary array provides a clear, fundamental way to achieve this without relying on advanced Java Collections. This approach helps in understanding basic array traversal and comparison logic.
Summary
- Duplicates in arrays can lead to data integrity issues and inefficiency.
- A
forloop-based approach involves iterating through the original array and using a nestedforloop to check for existence in a temporary array. - Unique elements are added to the temporary array, tracked by a
uniqueCount. - Finally, a new array of the exact size of
uniqueCountis created to store the unique elements, ensuring no redundant space.