简体   繁体   English

如何在列表中返回唯一值而不重新排序

[英]How to return unique values in a list without reordering

In the following code, I have an arraylist that contains duplicated values: 在下面的代码中,我有一个包含重复值的arraylist:

List<Double> fitnesses = new ArrayList<Double>();
fitnesses.add(5.0);
fitnesses.add(1.0);
fitnesses.add(5.0);
fitnesses.add(2.0);
fitnesses.add(4.0);
fitnesses.add(2.0);

I want to remove the duplicates and for that I used the following: 我想删除重复项,为此我使用了以下内容:

Set<Double> hashsetList = new HashSet<Double>(fitnesses);

The problem is that the output that I get is: 问题是我得到的输出是:

[1.0, 2.0, 4.0, 5.0]

The issue is that I don't want the values to be sorted. 问题是我不希望对值进行排序。 Is there any way to remove the duplicates without reordering 有没有办法删除重复项而不重新排序

You can use stream with distinct property. 您可以使用具有不同属性的流。
distinct() is a function of stream which is added in java 8 distinct()是在java 8中添加的流的函数

NOTE: If using java8 注意:如果使用java8

List<Double> distinctList = fitnesses.stream().distinct().collect(Collectors.toList());

NOTE: Before JAVA8 注意:在JAVA8之前

Set<Double> uniqueRecords = new LinkedHashSet<Double>();
for (Double value : fitnesses){
    uniqueRecords.add(value);
}
System.out.println(uniqueRecords);

Or we van use: 或者我们使用:

Set<Double> uniqueRecords = new LinkedHashSet<Double>(fitnesses); 

Output = [5.0, 1.0, 2.0, 4.0] 输出= [5.0,1.0,2.0,4.0]

如果您不想/不能使用java 8方法,可以将值插入到LinkedHashSet ,它会保留插入顺序。

You can achieve this with java 8 stream and distinct command: 您可以使用java 8 stream和distinct命令实现此目的:

List<Double> collect = fitnesses.stream()
                                .distinct() //this is where the magic happens
                                .collect(Collectors.toList());

Output: 输出:

[5.0, 1.0, 2.0, 4.0] [5.0,1.0,2.0,4.0]

In J8 as the other answer this is the most effiscient : 在J8作为另一个答案,这是最有效的:

List<Double> collect = fitnesses.stream()
                            .distinct() 
                            .collect(Collectors.toList());

You can also use a java.util.LinkedHashSet if you are not Java 8 如果您不是Java 8,也可以使用java.util.LinkedHashSet

Set<Double> hashsetList = new LinkedHashSet<Double>(fitnesses);

LinkedHashSet will preserve the order of added elements LinkedHashSet将保留添加元素的顺序

Using LinkedHashSet seems to work: 使用LinkedHashSet似乎工作:

public void test() throws InterruptedException {
    List<Double> fitnesses = new ArrayList<Double>();
    fitnesses.add(5.0);
    fitnesses.add(1.0);
    fitnesses.add(5.0);
    fitnesses.add(2.0);
    fitnesses.add(4.0);
    fitnesses.add(2.0);
    System.out.println("Original: "+fitnesses);
    // Get the unduplicated set.
    Set<Double> hashsetList = new LinkedHashSet<>(fitnesses);
    System.out.println("Deduplicated: "+hashsetList);
}

Original: [5.0, 1.0, 5.0, 2.0, 4.0, 2.0] 原文:[5.0,1.0,5.0,2.0,4.0,2.0]

Unduplicated: [5.0, 1.0, 2.0, 4.0] 无重复:[5.0,1.0,2.0,4.0]

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

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