Oct
26
Core Java program to remove duplicates from an array of Strings
Hey there! Welcome to ClearUrDoubt.com. In this post, we will look at a Core Java program to remove duplicates from an array of Strings. Here is the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
package com.clearurdoubt; import java.util.Arrays; public class RemoveDups { public static void main(String[] args) { String[] dups = new String[] {"ONE", "TWO", "THREE", "TWO", "ONE",}; String[] nodups = new String[dups.length]; System.out.println("Before removing duplicates: "); System.out.println(Arrays.toString(dups)); // Loop through the elements of dups array for(int i=0, j=0; i < dups.length; i++) { boolean isDuplicate = false; // Check if the current element in dups exists in nodups array. for(int k=0; k < nodups.length; k++) { if(nodups[k] == null) break; if(nodups[k].equals(dups[i])) { isDuplicate = true; break; } } // If the current element is not a duplicate, add to nodups array if(!isDuplicate) { nodups[j++] = dups[i]; } } // Let's find the true size of the nodups array int size = 0; // Remove nulls so that nodups array contains only the non-null elements for(int i = 0; i < nodups.length; i++) { if( nodups[i] == null) { size = i; break; } } // Create a new array with the "size" elements and copy the values so that nulls will be truncated nodups = Arrays.copyOf(nodups, size); System.out.println(); System.out.println("After removing duplicates: "); System.out.println(Arrays.toString(nodups)); } } |
Output: Happy Learning :). Please leave a reply in case of any Read more