- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to count unique elements in the array using java?
The interface Set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false −
If you try to add all the elements of the array to a Set, it accepts only unique elements −
Example
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CountingUniqueElements { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created ::"); int size = sc.nextInt(); int count = 0; int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i = 0; i<size; i++) { myArray[i] = sc.nextInt(); } System.out.println("The array created is :: "+Arrays.toString(myArray)); System.out.println("indices of duplicate elements in the array are elements :: "); Set set = new HashSet(); for(int i = 0; i<myArray.length; i++) { if(set.add(myArray[i])) { count++; System.out.println("Index :: "+i+" Element :: "+myArray[i]); } } } }
Output
Enter the size of the array that is to be created :: 6 Enter the elements of the array :: 45 45 45 69 32 69 The array created is :: [45, 45, 45, 69, 32, 69] indices of duplicate elements in the array are elements :: Index :: 0 Element :: 45 Index :: 3 Element :: 69 Index :: 4 Element :: 32
- Related Articles
- Count unique elements in array without sorting JavaScript
- How to reverse the elements of an array using stack in java?
- JavaScript Count the number of unique elements in an array of objects by an object property?
- C program to find the unique elements in an array.
- How to maintain the top count of array elements in MongoDB?
- Find count of positive and negative array elements in Java
- Counting unique elements in an array in JavaScript
- Deep count of elements of an array using JavaScript
- How to Alter Two Array Elements in Java
- Program to count number of sublists with exactly k unique elements in Python
- Count frequencies of all elements in array in Python using collections module
- Swift Program to Count the elements of an Array
- Find Count of Positive, Negative and Zero Elements in an Array in Java
- How to find a unique character in a string using java?
- How to sort Java array elements in ascending order?

Advertisements