How to get unique values ​​in a list

I have 2 text data files. I read these files using BufferReader and put the data of one column in a file in a List<String> .

I have duplicate data in each, but I need to have unique data in the first List in order to withstand duplicate data in the second List .

How to get unique values ​​from a List ?

+7
java list unique-values
source share
4 answers

You can execute one line using the intermediate Set :

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

In java 8, use distinct() for the stream:

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

Alternatively, do not use the List at all; just use Set (like a HashSet) from the very beginning for a collection in which you want to store only unique values.

+13
source share

Convert ArrayList to HashSet .

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

If for some reason you want to subsequently convert the set to a list, you can, but most likely will not need it.

 List<String> listWithUniqueValues = new ArrayList<>(setWithUniqueValues); 
+7
source share

I just understand that a solution can be useful to other people. will first be filled with duplicate values ​​from BufferReader.

 ArrayList<String> first = new ArrayList<String>(); 

To extract unique values, I just create a new ArrayList, like down:

 ArrayList<String> otherList = new ArrayList<>(); for(String s : first) { if(!otherList.contains(s)) otherList.add(s); } 

A lot of Internet posts all say to assign my Arraylist to a List, Set, HashTable or TreeSet. Can someone explain the difference in theory, while someone is better to use in practice? thnks for your time guys.

0
source share

In Java 8 :

  // List with duplicates List<String> listAll = Arrays.asList("A", "A", "B", "C", "D", "D"); // filter the distinct List<String> distinctList = listAll.stream() .distinct() .collect(Collectors.toList()); System.out.println(distinctList);// prints out: [A, B, C, D] 

this will also work with objects, but you may have to adapt the equals method.

0
source share

All Articles