简体   繁体   English

如何在List中获取唯一值

[英]How to get unique values in List

I have 2 text files with data. 我有2个带有数据的文本文件。 I am reading these files with BufferReader and putting the data of one column per file in a List<String> . 我正在使用BufferReader读取这些文件,并将每个文件的一列数据放在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 . 我每个都有重复的数据,但我需要在第一个List有唯一的数据来对抗第二个List的重复数据。

How can I get unique values from a List ? 如何从List获取唯一值?

It can be done one one line by using an intermediate Set : 它可以通过使用中间Set来完成一行:

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

In java 8, use distinct() on a stream: 在java 8中,在流上使用distinct()

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

Alternatively, don't use a List at all; 或者,根本不要使用List; just use a Set (like HashSet) from the start for the collection you only want to hold unique values. 只需从集合的开头使用Set(如HashSet),您只想拥有唯一值。

Convert the ArrayList to a HashSet . ArrayList转换为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);

In Java 8 : 在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 will probably have to adapt your equals method. 这也适用于对象,但您可能需要调整equals方法。

i just realize a solution may be it can be helpful for other persons. 我只是意识到解决方案可能对其他人有帮助。 first will be populated with duplicated values from BufferReader. 首先将使用BufferReader中的重复值填充。

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

To extract Unique values i just create a new ArrayList like down: 要提取唯一值,我只需创建一个新的ArrayList,如下:

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

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

A lot of post in internet are all speaking to assign my Arraylist to a List , Set , HashTable or TreeSet. 互联网上的很多帖子都在说我将Arraylist分配给List,Set,HashTable或TreeSet。 Can anyone explain the difference in theory and whitch one is the best tu use in practice ? 任何人都可以解释理论上的差异,并且在实践中是最好的用途吗? thnks for your time guys. 为你的时间而努力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM