Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique values from array

Tags:

I have an Array from which i want to remove Duplicate items.

for(int data1=startpos;data1<=lastrow;data1++) {
    String movie_soundtrk=cells.getCell(data1,Mmovie_sndtrk_cl).getValue().toString();
    al.add(movie_soundtrk);
}

String commaSeparated=al.toString();
String [] items = commaSeparated.split(",");
String[] trimmedArray = new String[items.length];
for (int i = 0; i < items.length; i++) {
    trimmedArray[i] = items[i].trim();
}

Set<String> set = new HashSet<String>();
Collections.addAll(set, trimmedArray);

System.out.println(set);

But this is not giving me unique Values from Array.

My Array:- {English, French, Japanese, Russian, Chinese Subtitles,English, French, Japanese, Russian, Chinese Subtitles}

Out Put :- [Japanese, Russian, French, Chinese Subtitles], Chinese Subtitles, [English, English]

like image 292
Code Hungry Avatar asked Dec 10 '12 07:12

Code Hungry


People also ask

How do I find unique values in an array?

You can find the distinct values in an array using the Distinct function. The Distinct function takes the array as an input parameter and returns another array that consists only of the unique, or non-duplicate, elements.

How do I get unique values from an array in Excel?

In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.

How do I find unique elements in 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.


2 Answers

You can do it in one line in java 7:

String[] unique = new HashSet<String>(Arrays.asList(array)).toArray(new String[0]);

and shorter and simpler in java 8:

String[] unique = Arrays.stream(array).distinct().toArray(String[]::new);
like image 192
Bohemian Avatar answered Oct 16 '22 12:10

Bohemian


HashSet will do the job.

You can try this:

List<String> newList = new ArrayList<String>(new HashSet<String>(oldList));
like image 33
flk Avatar answered Oct 16 '22 12:10

flk