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
?
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.
unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With