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.

Disclaimer:-

Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.

 

8. Array

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?