[英]How to return unique values in a list without reordering
在下面的代碼中,我有一個包含重復值的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);
我想刪除重復項,為此我使用了以下內容:
Set<Double> hashsetList = new HashSet<Double>(fitnesses);
問題是我得到的輸出是:
[1.0, 2.0, 4.0, 5.0]
問題是我不希望對值進行排序。 有沒有辦法刪除重復項而不重新排序
您可以使用具有不同屬性的流。
distinct()
是在java 8中添加的流的函數
注意:如果使用java8
List<Double> distinctList = fitnesses.stream().distinct().collect(Collectors.toList());
注意:在JAVA8之前
Set<Double> uniqueRecords = new LinkedHashSet<Double>();
for (Double value : fitnesses){
uniqueRecords.add(value);
}
System.out.println(uniqueRecords);
或者我們使用:
Set<Double> uniqueRecords = new LinkedHashSet<Double>(fitnesses);
輸出= [5.0,1.0,2.0,4.0]
如果您不想/不能使用java 8方法,可以將值插入到LinkedHashSet
,它會保留插入順序。
您可以使用java 8 stream和distinct
命令實現此目的:
List<Double> collect = fitnesses.stream()
.distinct() //this is where the magic happens
.collect(Collectors.toList());
輸出:
[5.0,1.0,2.0,4.0]
在J8作為另一個答案,這是最有效的:
List<Double> collect = fitnesses.stream()
.distinct()
.collect(Collectors.toList());
如果您不是Java 8,也可以使用java.util.LinkedHashSet
Set<Double> hashsetList = new LinkedHashSet<Double>(fitnesses);
LinkedHashSet將保留添加元素的順序
使用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);
}
原文:[5.0,1.0,5.0,2.0,4.0,2.0]
無重復:[5.0,1.0,2.0,4.0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.