I\'m writing a code where I have an int[a] and the method should return the number of unique values. Example: {1} = 0 different values, {3,3,3} = 0 different values, {1,2} = 2 d
You can use a HashSet
, which can only contain unique elements. The HashSet
will remove the duplicated items and you can then get the size of the set.
public static int differentValuesUnsorted(int[] a) {
Set unique = new HashSet();
for (int val : a) {
unique.add(val); // will only be added if a is not in unique
}
if (unique.size() < 2) { // if there are no different values
return 0;
}
return unique.size();
}