Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique values in List

I have 2 text files with data. I am reading these files with BufferReader and putting the data of one column per file in a List<String>.

I have duplicated data in each one, but I need to have unique data in the first List to confront with the duplicated data in the second List.

How can I get unique values from a List?

like image 772
Junior Fulcrum Avatar asked Oct 01 '14 22:10

Junior Fulcrum


People also ask

How do I get a list of unique values in a column?

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.

What does unique () do in Python?

unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.


2 Answers

It can be done one one line by using an intermediate Set:

List<String> list = new ArrayList<>(new HashSet<>(list));

In java 8, use distinct() on a stream:

List<String> list = list.stream().distinct().collect(Collectors.toList());

Alternatively, don't use a List at all; just use a Set (like HashSet) from the start for the collection you only want to hold unique values.

like image 189
Bohemian Avatar answered Sep 29 '22 21:09

Bohemian


Convert the ArrayList to a HashSet.

List<String> listWithDuplicates; // Your list containing duplicates
Set<String> setWithUniqueValues = new HashSet<>(listWithDuplicates);

If for some reason, you want to convert the set back to a list afterwards, you can, but most likely there will be no need.

List<String> listWithUniqueValues = new ArrayList<>(setWithUniqueValues);
like image 35
Robby Cornelissen Avatar answered Sep 29 '22 21:09

Robby Cornelissen