Java Online Compiler
Example: CountDistinctElementsUsingHashSet in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CountDistinctElementsUsingHashSet import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { // Step 1: Define the input array int[] arr = {10, 20, 10, 30, 40, 20, 50}; // Step 2: Create a HashSet to store distinct elements Set<Integer> distinctElements = new HashSet<>(); // Step 3: Iterate through the array and add each element to the HashSet // HashSet automatically handles duplicates; only unique elements are added for (int element : arr) { distinctElements.add(element); } // Step 4: The size of the HashSet represents the count of distinct elements int distinctCount = distinctElements.size(); // Step 5: Print the result System.out.println("Original Array: " + java.util.Arrays.toString(arr)); System.out.println("Number of distinct elements (HashSet): " + distinctCount); } }
Output
Clear
ADVERTISEMENTS