Count Distinct Elements

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 49:-  Count Distinct Elements

To count the distinct elements in an array, you can use a set data structure in Java. A set is a collection that does not allow duplicate elements, so adding elements to a set will automatically eliminate duplicates. Once you have added all elements of the array to the set, the size of the set will give you the count of distinct elements.

Here's a Java method to count the distinct elements in an array:

javaCopy code

import java.util.HashSet; import java.util.Set; public class DistinctElementCounter {    public static int countDistinctElements(int[] arr) {        Set<Integer> distinctElements = new HashSet<>();        for (int element : arr) {            distinctElements.add(element);        }        return distinctElements.size();    }    public static void main(String[] args) {        int[] array = {1, 2, 3, 2, 4, 1, 5, 6, 5, 7};        int distinctCount = countDistinctElements(array);        System.out.println("Number of distinct elements: " + distinctCount); // Output: 7    } }

In this example, we have a method countDistinctElements that takes an integer array arr as an argument. Inside the method, we create a HashSet called distinctElements to store the unique elements. Then, we iterate through the array and add each element to the set using the add method. Since a set does not allow duplicates, only distinct elements will be added to the set. Finally, we return the size of the set, which gives us the count of distinct elements.

In the main method, we demonstrate how to use the countDistinctElements method with a sample array. The output will be the count of distinct elements in the array, which is 7 in this case.

Using a set is an efficient and convenient way to count the distinct elements in an array. It automatically takes care of eliminating duplicates, and you can easily get the count by querying the size of the set.

8. Array

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support