0

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?

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Shinta Dwi
  • 71
  • 1
  • 6

3 Answers3

3

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.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • 1
    Almost... use a `LinkedHashSet` to maintain iteration order, otherwise the new array will be essentially be in random order – Bohemian Dec 29 '13 at 01:41
  • 1
    @Bohemian: that was what I thought as well, but after executing it 20 times the result is always as is shown. Even when you mix the values in the original array, they are displayed from low to high. -- Edit: oh okay, iteration order. The `HashSet` must order them low to high, `LinkedHashSet` indeed maintains the original order. – Jeroen Vannevel Dec 29 '13 at 01:45
1

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

it's something really easy to make in php, use the function : array_unique() http://www.php.net/manual/en/function.array-unique.php

menardmam
  • 9,860
  • 28
  • 85
  • 113