且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据Java中另一个arraylist中的对象值对arraylist进行排序

更新时间: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

  • x> y ,如果 x 在A中的 y 之前出现.
  • x< y ,如果 x 在A中的 y 之后出现.
  • x = y ,如果 x = y
  • x > y, if x appears before y in A.
  • x < y, if x appears after y in A.
  • x = y, if x = y

因此,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).