Java 如何按2个字段对arraylist排序?

Java 如何按2个字段对arraylist排序?,java,Java,我得到了一个包含下一个数据的数组列表:coordX(int)、coordY(int)、length(int)、position(String)。我按照length字段对数组进行排序。如果长度等于位置字段,我如何给予优先级(优先级将具有具有水平位置的长度)。例如,给定输入: coordX = 1 , coordY = 0 , length = 2 , position - vertical coordX = 5 , coordY = 3 , length = 2 , po

我得到了一个包含下一个数据的数组列表:
coordX
(int)、
coordY
(int)、
length
(int)、
position
(String)。我按照
length
字段对数组进行排序。如果长度等于
位置
字段,我如何给予优先级(优先级将具有具有水平位置的长度)。例如,给定输入:

coordX = 1  ,  coordY = 0   , length = 2  ,  position  - vertical
coordX = 5  ,  coordY = 3   , length = 2  ,  position  - horizontal
coordX = 1  ,  coordY = 6   , length = 4  ,  position  - horizontal
coordX = 3  ,  coordY = 6   , length = 1  ,  position  - "1x1"
输出应为:

coordX = 1  ,  coordY = 6   , length = 4  ,  position  - horizontal
coordX = 5  ,  coordY = 3   , length = 2  ,  position  - horizontal
coordX = 1  ,  coordY = 0   , length = 2  ,  position  - vertical
coordX = 3  ,  coordY = 6   , length = 1  ,  position  - "1x1"
以下是我所拥有的:

    public static void insertionSort(ArrayList<sort> srt) {
    int i,j;
    for (i = 1; i < srt.size(); i++) {
        sort tmp = srt.get(i);
        j = i;
        while ((j > 0) && (srt.get(j - 1).length > tmp.length)) {
            srt.set(j, srt.get(j - 1));
            j--;
        }
        srt.set(j, tmp);
    }
}
publicstaticvoidinsertionsort(arraylistsrt){
int i,j;
对于(i=1;i0)和&(srt.get(j-1.length>tmp.length)){
srt.set(j,srt.get(j-1));
j--;
}
srt.set(j,tmp);
}
}
坐标类的可能结构

class YourClass {
    int length;
    public String position;
    int coordX;
    int coordY;

    public int getLength() {
        return length;
    }

    public String getPosition() {
        return position;
    }

    public int getCoordX() {
        return coordX;
    }

    public int getCoordY() {
        return coordY;
    }
}


首先,有。这样,它看起来像:
Collections.sort(list,Comparator.comparingit(s->s.length)。然后比较(s->s.position))
。您应该使用
Collections.sort
并编写一个比较器,让您的类实现Comparables。这是否回答了您的问题@povisenko这个问题是关于Java的,链接到Javascript的副本是不正确的。
        list.sort(Comparator.comparing(YourClass::getLength).reversed()
                .thenComparing(YourClass::getPosition));
        // or with no getters

        list.sort(Comparator.comparing((YourClass cl) -> cl.length).reversed()
                .thenComparing((YourClass cl) -> cl.position));

class YourClass {
    int length;
    public String position;
    int coordX;
    int coordY;

    public int getLength() {
        return length;
    }

    public String getPosition() {
        return position;
    }

    public int getCoordX() {
        return coordX;
    }

    public int getCoordY() {
        return coordY;
    }
}