• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calculating number of unique values in an integer array - any help  RSS feed

 
celine scarlett
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a simple array with ten integer values. I can get the 'for' loop to count the total number of values in the array, the maximum etc, but how do I get it to calculate the total number of unique/distinct values in the array.

My current code is as follows,



This code calculates the maximum value in the array. Any idea how to change this?

Any help really appreciated!
 
Don Morgan
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One simple way to get the total number of unique values is to place them all on a HashMap, using the value itself as the key, and then the number of unique values is the size of the HashMap.
 
Abhijeet Thacker
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On the same path, but with little difference, when u add a member from the Array to your hasmap u can verify with containsKey() method of HashMap. If u get true then move on to Next element in Array, other wise add a member from array to HashMap.

At the end HashMap.size() and u can find the total number of unique member in your array.

This way it mightget improve the performance
 
celine scarlett
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks for the replies. Have a great week.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!