# How to find the number of unique values in an Array

• 09-11-2011, 02:22 PM
djbeko06
How 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.
How can I get 2?

Many thank
• 09-11-2011, 03:46 PM
Norm
Re: 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, 06:02 PM
eRaaaa
Re: How to find the number of unique values in an Array
Quote:

Originally Posted by djbeko06
e.g.

Do you mean String a[] = {"aab","aba","aca","aab","adc","zzz","aca"}; ? :)

Quote:

How can I get 2?
System.out.println(a.length-new HashSet<String>(Arrays.asList(a)).size());
:P
• 09-11-2011, 06:06 PM
Norm
Re: 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.

• 09-11-2011, 06:17 PM
Norm
Re: 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)
"zzz", 4
"aca" 3 (-1 dup)

Are there 2 or 3 unique elements in the list? aba, adc and zzz
• 09-12-2011, 10:28 AM
djbeko06
Re: 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, 10:44 AM
srivempala
Re: 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, 10:45 AM
JosAH
Re: How to find the number of unique values in an Array
Quote:

Originally Posted by djbeko06
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”

Use two Set<String> collections; one to store each element in your array and the other one to store the duplicates (already present in the first set). At the end remove everything in the first set that is also present in the second set.

kind regards,

Jos