简体   繁体   中英

How to return unique values in a list without reordering

In the following code, I have an arraylist that contains duplicated values:

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

NOTE: If using java8

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

NOTE: Before 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]

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

You can achieve this with java 8 stream and distinct command:

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

Output:

[5.0, 1.0, 2.0, 4.0]

In J8 as the other answer this is the most effiscient :

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

You can also use a java.util.LinkedHashSet if you are not Java 8

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

LinkedHashSet will preserve the order of added elements

Using LinkedHashSet seems to work:

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]

Unduplicated: [5.0, 1.0, 2.0, 4.0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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