14

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?

4

4 回答 4

22

可以通过使用中间体来完成一行Set

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

在 java 8 中,distinct()在流上使用:

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

或者,根本不要使用列表;只需从一开始就为您只想保存唯一值的集合使用 Set(如 HashSet)。

于 2014-10-01T23:13:17.270 回答
11

将 转换ArrayListHashSet.

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

如果出于某种原因,您想在之后将集合转换回列表,您可以,但很可能不需要。

List<String> listWithUniqueValues = new ArrayList<>(setWithUniqueValues);
于 2014-10-01T22:58:06.010 回答
3

在 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]

这也适用于对象,但您可能必须调整您的 equals 方法。

于 2017-11-16T10:21:57.537 回答
0

我只是意识到一个解决方案可能对其他人有帮助。首先将填充来自 BufferReader 的重复值。

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

要提取唯一值,我只需创建一个新的 ArrayList,如下所示:

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

    for(String s : first) {
        if(!otherList.contains(s))
            otherList.add(s);
    }

互联网上的很多帖子都在谈论将我的 Arraylist 分配给 List 、 Set 、 HashTable 或 TreeSet 。任何人都可以解释理论上的区别,而其中一个是实践中最好的吗?谢谢你们的时间。

于 2014-10-01T23:10:27.783 回答