Sort String list in pre-defined custom ordering

后端 未结 1 1550
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 13:27

I have this project in which the program asks the user how many times it should run. During each run a list is created and elements are added. These elements in the array are so

1条回答
  •  别那么骄傲
    2021-01-29 14:02

    You can build your own Comparator:

    import java.util.Comparator;
    
    public class MyComparator implements Comparator {
    
        private int[] charRank;
    
        public MyComparator() {
            char[] charOrder = {'Q','W','E','R','T','Y','U','I','O','P','L','K','J','H','G','F','D','S','A','Z','X','C','V','B','N','M'};
            this.charRank = new int[26];
            for(int i=0; i<25; i++) {
                this.charRank[charToInt(charOrder[i])] = i; 
            }
        }
    
        public int compare(String s1, String s2) {
            // returns
            // Positive integer if s1 greater than s2
            // 0 if s1 = s2
            // Negative integer if s1 smaller than s2
            s1 = s1.toUpperCase();
            s2 = s2.toUpperCase();
            int l = Math.min(s1.length(), s2.length());
            int charComp;
            for(int i=0; i

    Then, you just have to run:

    Arrays.sort(entryArray, new MyComparator());
    

    Some explanations now.

    The constructor of MyComparator builds an array of ranks for each of your letter. In practice it will begin with {18, 23, 21, ... } because 'A' is in the 18th place, 'B' in the 23rd...

    Then, when you compare two strings s1 and s2, characters are compared in the lexicographic order one by one.

    • Imagine the first n characters are identical, and now, you compare c1 and c2. If the rank of c1 is lower than then rank of c2, then you have to return a negative integer since s1 comes before s2 in the lexicographic order (s1 is smaller than s2). If the rank of c1 is greater than the rank of c2, it is the contrary. If both ranks are equals c1 and c2 are equals and you have to look at the next character.
    • If you reach the end of one string, then either the two string are equals, either one string is the prefix of another. In each case, it is enough to compare the lengths of the strings: if s1 is shorter, it comes first in the lexicographic order, it is smaller, you have to return a negative integer.

    And here you go. I hope it was what you were waiting for.

    @Edit: the s1 = s1.toUpperCase() is just to avoid the pain to distinguish upper and lower case letters. If you prefer to work with lower case letters, just change it to s1 = s1.toLowerCase(), change the method intToChar to return c-97 (ascii code for a lower case 'a') and naturally, specify the charOrder array in the constructor using lower case letters.

    0 讨论(0)
提交回复
热议问题