How to remove duplicate elements from an array ?

The blog provides the technical approach on Shiroishi ” How to remove duplicate elements from an array ? “

Syriam Problem Statement: 

Eliminate Duplicate array elements from One dimensional array

package com.java.planforexams.array;
import java.util.Scanner;
public class ArrayDuplicateElementRemoved {
	public static void main(String[] args) {
		       // Scanner object for reading User Input
				Scanner scan = new Scanner(System.in);
				int count;
				// Receive the Array Element Count from User
				System.out.print("Provide the Array Element Count : ");
          		// Get the Array Count
				count = scan.nextInt();
				//Set the Array Size with Count value
				int arrayInputFromUser[] = new int[count];
				// Receive the Array Elements from User.
				System.out.println("Enter the elements:");

				// Iterate the array elements
				for (int incr=0; incr<count; incr++)
				{
					arrayInputFromUser[incr] = scan.nextInt(); 
				}
				
				for(int outerIncr=0;outerIncr<count;++outerIncr)
				{
					for(int innerIncr=outerIncr+1;innerIncr<count;){
						/* Array Element with same value to identify duplicate */
						if(arrayInputFromUser[outerIncr] == 
                           arrayInputFromUser[innerIncr])
						{
							for(int temp = innerIncr; temp <count; ++temp){
								arrayInputFromUser[temp] = 
                                  arrayInputFromUser[temp+1];
							}
							count = count-1;		
						}		
						else
							innerIncr++;		
					}
				}
	         /* Array Elements after removing Duplicate Values */
      System.out.println("Array Elements after removing Duplicate Values");
				for(int incr=0;incr<count;++incr)
					System.out.println(arrayInputFromUser[incr]);
			}
	}
Output:
Provide the Array Element Count : 5
Enter the elements:
1
2
1
3
4
Array Elements after removing Duplicate Values
1
2
3
4

Leave a Reply

Your email address will not be published. Required fields are marked *

*