How can I find the number of unique values of a String array?

e.g.

double a[] = {aab,aba,aca,aab,adc,zzz,aca};

How can I get 2?

Many thank

Printable View

- 09-11-2011, 01:22 PMdjbeko06How to find the number of unique values in an Array
How can I find the number of unique values of a String array?

e.g.

double a[] = {aab,aba,aca,aab,adc,zzz,aca};

How can I get 2?

Many thank - 09-11-2011, 02:46 PMNormRe: How to find the number of unique values in an Array
What classes and methods can you use for this?

Sort the array and then scan it

Use a Map to keep a count of the occurences of each value then scan it - 09-11-2011, 05:02 PMeRaaaaRe: How to find the number of unique values in an Array
- 09-11-2011, 05:06 PMNormRe: How to find the number of unique values in an Array
eRaaaa You could explain how your very clever code works in case the OP is a beginner and not familiar with the techniques you are using.

Does your code produce the correct answer? See next post. - 09-11-2011, 05:17 PMNormRe: How to find the number of unique values in an Array
Go thru the list adding one to count if unique, subtracting 1 if a duplicate:

"aab", 1

"aba", 2

"aca", 3

"aab", 2 (-1 because a dup)

"adc", 3

"zzz", 4

"aca" 3 (-1 dup)

Are there 2 or 3 unique elements in the list? aba, adc and zzz - 09-12-2011, 09:28 AMdjbeko06Re: How to find the number of unique values in an Array
Sorry this is the full question:

Create a static method called countUnique(String s[]) that accepts an array of strings as a parameter and returns the number of unique strings in the array. A unique string would be a string that occurs only once in the array. For example countUnique(new int[]{“aaa”,”aba”,”aba”,”ccc”}) would return 2 as there are 2 unique strings in the array: “aaa” and “ccc” - 09-12-2011, 09:44 AMsrivempalaRe: How to find the number of unique values in an Array
I think better to put it in set. then set will not allow duplicates so u can get unique values and count those elament su can get 2.

- 09-12-2011, 09:45 AMJosAHRe: How to find the number of unique values in an Array