[英]Sorting an arraylist based on objects value in another arraylist in Java
我在排序數組列表時遇到問題。 在一個類中,我有兩個不同對象的數組列表,我們可以調用對象 Foo 和 Bar。
public class Foo() {
int value;
//Some other fields, and setters and getters.
}
public class Bar() {
int id;
//Same here...
}
所以列表 fooList 可以完全打亂。 假設我有 16 個 Foo,但值為 5 的 Foo 可以在索引 13 上,依此類推。
我想要做的是在這些值之后命令 barList 匹配 fooList。 如果值為 5 的 Foo 在索引 13 上,我希望值為 5 的 Bar 在索引 13 上。我最后一次嘗試是這樣,但沒有成功。
HashMap<Integer, Integer> positions = new HashMap<>();
for(int i=0;i<fooList.size();i++){
positions.put(foo.get(i).getValue, i);
}
Collections.sort(barList, new Comparator<Bar>(){
public int compare(Bar obj1, Bar obj2){
return positions.get(barList.indexOf(obj1)) -
positions.get(barList.indexOf(obj2));
}
});
有沒有人知道如何以有效的方式做到這一點?
我不確定您為什么使用barList
元素的索引來查看地圖positions
。
這應該可以幫助你
Collections.sort(barList, new Comparator<Bar>() {
@Override
public int compare(Bar o1, Bar o2) {
return positions.get(o1.getId()) - positions.get(o2.getId());
}
});
這可以通過單行來簡化
Collections.sort(barList, Comparator.comparingInt(bar -> positions.get(bar.getId())));
基本上,問題歸結為:
給定兩個整數列表 A = {a 1 , a 2 ...a n } 和 B = {b 1 , b 2 , ...b m },根據其中元素出現的位置對列表 B 進行排序第一個列表,A。
對於 B 中的兩個元素x , y
因此, Bar
的比較器函數必須比較特定元素在Foo
中出現的位置(基於上述)。
注意:這假設(如您所說) Bar
中沒有Foo
沒有的元素。 ( Bar
中的元素是Foo
元素的子集)。
我首先在值上索引barList
項目,以便可以快速找到具有適當值的Bar
實例。 然后使用它將fooList
轉換為新的barList
。 沿線的東西:
Map<Integer, Bar> barMap = barList
.stream()
.collect(Collectors
.toMap(
Bar::getValue,
Function.identity());
barList = fooList
.stream()
.map(Foo::getValue)
.map(barMap::get)
.collect(Collectors.toList());
我認為這在時間上必須是最佳的。 為了內存,你必須在這里建立一個barMap
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.