Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of unique elements?

Given an array like the one below, I was wondering if there is an easy way to turn this array into an array with unique values only?

This is given:

   numbers={5,5,4,3,1,4,5,4,5} 

Turn it into a result array like this, preserving the original order:

   {5,1,2,3,4} 
like image 836
AnchovyLegend Avatar asked Feb 01 '13 22:02

AnchovyLegend


People also ask

How do I get unique elements from an array in C++?

Finding the non repeating element in an array can be done in 2 different ways. Method 1: Use two loops, one for the current element and the other to check if the element is already present in the array or not. Method 2: Traverse the array and insert the array elements and their number of occurences in the hash table.

How do you count the number of unique values in an array?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears. The resulting array looks like {1;2;1;1;1;1}.


1 Answers

In Java 8, use IntStream to get unique elements of an array

int[] noDuplicates = IntStream.of(array).distinct().toArray();

The simplest way would be to create set from the array.

Integer[] array = ...
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(array ));

and then you can retrieve the array using:

set.toArray()

use LinkedHashSet if you want to maintain the order or TreeSet if you want to have it sorted.

like image 175
zibi Avatar answered Sep 23 '22 02:09

zibi