更新时间:2023-01-07 21:06:18
我不确定为什么要使用barList
中元素的索引来查找地图positions
.
I'm not sure why you are using the index of an element in barList
to look into the map positions
.
这应该对您有帮助
Collections.sort(barList, new Comparator<Bar>() {
@Override
public int compare(Bar o1, Bar o2) {
return positions.get(o1.getId()) - positions.get(o2.getId());
}
});
可以通过单线简化此操作
This can be simplified with a one-liner
Collections.sort(barList, Comparator.comparingInt(bar -> positions.get(bar.getId())));
基本上,问题可以归结为:
Basically, the problem boils down to this:
给出两个整数列表A = {a 1 ,a 2 ... a n },B = {b 1 ,b 2 ,... b m },根据元素在第一个列表A中的出现位置对列表B进行排序
Given two lists of integers A = {a1, a2...an} and B = {b1, b2, ...bm}, sort the list B based on the position of occurrence of the element in the first list, A.
对于B中的两个元素 x , y
For two elements x, y in B
因此,Bar
的比较器函数必须比较Foo
中特定元素出现的位置(基于上述内容).
So, the comparator function for Bar
has to compare the position at which a particular element has appeared in Foo
(based on the above).
注意::这假设(如您所说)假设Bar
中没有没有元素,而Foo
中没有元素. (Bar
中的元素是Foo
中元素的子集.)
NOTE: This assumes (as you have said) that there is no element in Bar
that is not there in Foo
. (The elements in Bar
are a subset of the elements in Foo
).