Remove Duplicate Elements From Array

Description

To delete duplicate elements in an array using set store the elements
of array into set. As set does no contain the duplicate, it will give
output after removal of duplicate.

Example: Input: 4 1 3 4 1
         Output: 1 3 4

C/C++

Code in C is not available. Please visit java code.

Java

/* Java program to delete duplicate elements in an array using set*/
//Save it as DeleteDuplicateElementUsingSet.java

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class DeleteDuplicateElementUsingSet {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the size of array : ");
        int n = scanner.nextInt();

        int arr[] = new int[n];
        
        //Taking array elements as input
        System.out.println("Enter the elements of the array : ");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }
        
        //Printing the array elements
        System.out.println("The elements you entered are : ");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        
        //Declaring the set
        Set<Integer> set = new HashSet<>();
        
        //Storing the array elements into set
        for(int i=0;i<arr.length;i++) {
            set.add(arr[i]);
        }
        
        //Printing the elements of array
        //As set does not contain the duplicate it will print unique elements
        
        /*
         * for(int var : set) { System.out.print(var+" "); }
         */
         
        System.out.println("\nThe elements of array after removal of duplicate : ");
        set.forEach(e->System.out.print(e+" "));
    }
}
Input:
Enter the size of array : 
5
Enter the elements of the array : 
4
1
3
4
1

Output:
The elements you entered are : 
4 1 3 4 1 
The elements of array after removal of duplicate : 
1 3 4

Related Programs

1) Program to Print How Many Numbers Smaller than Current Number
2) Program to make pair of elements alternatively
3) Program to form a number using entered digits
4) Program to merge two sorted arrays
5) Program to swap maximum and minimum element of Array
6) Program to Add two Matrices
7) Program to Multiply two Matrices
8) Program to Rearrange an array such that arr[i]=i
9) Program to Find Mode of a Array
10) Program to Check Array is Perfect or Not
Share Me

Leave a Reply