简体   繁体   中英

How to sort by two criteria in JAVA?

I got an ArrayList which contains next data: coordX, coordY, length, position ( position can be of 3 types: vertical, horizontal or 1x1 ). Using insertion method, I sort this descending by length. How can i give priority in case if length is equal for that value of length who has the horizontal position.For given input:

(1;0)  ,  length = 2  ,  position - vertical
(1;6)  ,  length = 4  ,  position - horizontal
(3;4)  ,  length = 3  ,  position - horizontal
(3;6)  ,  length = 1  ,  position - 1x1
(4;0)  ,  length = 1  ,  position - 1x1
(5;3)  ,  length = 2  ,  position - horizontal
(6;7)  ,  length = 2  ,  position - vertical
(7;5)  ,  length = 2  ,  position - horizontal

the output should be:

(1;6)  ,  length = 4  ,  position - horizontal
(3;4)  ,  length = 3  ,  position - horizontal
(5;3)  ,  length = 2  ,  position - horizontal
(7;5)  ,  length = 2  ,  position - horizontal
(1;0)  ,  length = 2  ,  position - vertical
(6;7)  ,  length = 2  ,  position - vertical
(3;6)  ,  length = 1  ,  position - 1x1
(4;0)  ,  length = 1  ,  position - 1x1

This is what i have at the moment:

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);
        }
        for(sort e : srt) {
            System.out.println("("+e.coordX+";"+e.coordY+")"+"  ,  length= "+e.length+"  ,  position - "+e.pozitie);
        }

}

This part of code is responsabile only for sorting by the length.

Try the following:

You need to check first on the length and then if they are equal, check on the position.

            while ((j > 0) && (srt.get(j - 1).length < tmp.length
                    || (srt.get(j - 1).length == tmp.length
                            && srt.get(j - 1).position
                                    .compareTo(tmp.position) > 0))) {
                srt.set(j, srt.get(j - 1));
                j--;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM