Write a program to print distinct elements of an array by avoiding duplicate numbers Using Java

Write a program to print distinct elements of an array by avoiding duplicate numbers Using Java

Write a program to print distinct elements of an array by avoiding duplicate numbers

This article will help you to understand “Java program to print distinct elements of an array”.

Java program to print distinct elements of an array to get distinct elements from an array, we will store all elements of the array in HashSet which will avoid duplicate elements.

Java program to print distinct elements of an array

 

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

public class DistinctArrayElements {

public void printDistinctElements(int[] inputArray)
{
Set elementSet = new HashSet();

for(int i = 0; i<inputArray.length; i++)
{
elementSet.add(inputArray[i]);
}

System.out.println(“Distinct Elements”);
for (int i : elementSet) {
System.out.println(i);
}
}

public static void main(String args[])
{
DistinctArrayElements obj = new DistinctArrayElements();

int[] givenArray = {1,3,4,5,1,4,7,9,7};

obj.printDistinctElements(givenArray);

}
}

Output

Distinct Elements 1 3 4 5 7 9

Leave a Reply

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