If i have an array with say 4 values, and all the values are the same. Is it possible to use something like array.length or size, so that the length returned is only 1.
-
You would need to create a static helper method somewhere that takes the array as an argument. In Java you can't add new methods or overwrite methods on the array object. – JustinKSU Jun 26 '18 at 16:15
-
1Add all to a `Set` and return the size of said `Set` – achAmháin Jun 26 '18 at 16:16
7 Answers
use something like below and remove the Duplicate Element in your array and generate set from your array :
Integer[] array = ...
Set<Integer> mySet = new LinkedHashSet<Integer>(Arrays.asList(array ))
your array stay untouched and you can find out the size by :
mySet.size()

- 563
- 1
- 9
- 25
Not with the Array API. You have to build a Set
of the elements in the array and thus, since the Set
can't contain duplicates, it's .size()
methods will return 1.
(Actually, Set::size()
returns the number of distinct elements put in the Set
)

- 20,627
- 6
- 47
- 86
You could try using Map with handles unique values?
Or make an static util class where you parse the array and find the unique values and return the number of them.
But the simplest way is, uniquest values from a Integer array list, from here:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);

- 1,036
- 11
- 15
For non-primitive array, you can create a set and return the size of this set:
Integer[] array = new Integer[4];
array[0] = 1;
array[1] = 1;
array[2] = 1;
array[3] = 1;
Set<Integer> set = new HashSet<>(Arrays.asList(array));
System.out.println(set.size()); //1

- 27,410
- 9
- 53
- 103
java.util.List
or java.util.Arrays
doesn't provide a functionality like this but you can use the Stream-API to get something similar:
int nrOfUniqueElems = Arrays.stream(myArray).distinct().count();

- 5,323
- 1
- 11
- 27
You can use the following code sample to get it done in 1 line
new HashSet(Arrays.asList(<your-array-object>).size();

- 189
- 1
- 11
You can run a for loop that will add elements to another array if the elements are unique, and if they are the same as the other array elements, they will not be added to the new array. Here is an example:
public class ChapterOneBasics {
public static void main(String[] args){
int ar[] = {1, 1, 1, 1};
int ar2[] = {1};
for(int x = 0; x <= ar.length; x++) {
if(x > 0) {
if(ar[x] != ar[x - 1]) {
ar2[x] = ar[x];
}
}
System.out.println(ar2.length + " is the size of the array uniqueness.");
}
}
}
output:
1 is the size of the array uniqueness.

- 2,152
- 1
- 10
- 27