I have an array with values:
[1,2,2,8,8,10,10,10,11,]
I want my array like this:
[1,2,8,10,11]
How can I remove all the entries so only unique values remain?
I have an array with values:
[1,2,2,8,8,10,10,10,11,]
I want my array like this:
[1,2,8,10,11]
How can I remove all the entries so only unique values remain?
You mean the entries should be unique.
I happen to have answered a very similar question just a few minutes ago, so here's the adjusted code:
public class Main {
public static void main(String[] args) {
Integer[] arr = {1, 2, 2, 8, 8, 10, 10, 10, 11 };
System.out.println(Arrays.toString(arr));
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
arr = new Integer[set.size()];
arr = set.toArray(arr);
System.out.println(Arrays.toString(arr));
}
}
Output
[1, 2, 2, 8, 8, 10, 10, 10, 11]
[1, 2, 8, 10, 11]
Once again: the code can be inefficient if you're working with very large collections because it throws your data trough a few collections.
A HashSet
automatically removes duplicates so all you have to do is insert your values in that collection.
If you want unique values, you don't want an array, you want a Set:
Set<Integer> numbers = new LinkedHashSet<Integer>();
The LinkedHashSet
implementation of Set
maintains the iteration order to be the same as insertion
order.
it's something really easy to make in php, use the function : array_unique() http://www.php.net/manual/en/function.array-unique.php