Java Online Compiler
Example: Remove Duplicates from Array using For Loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// 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)); } }
Output
Clear
ADVERTISEMENTS