Sorting an array of String with custom ordering

后端 未结 4 1443
不知归路
不知归路 2020-11-30 10:27

I have a String array:

 String[] str = {\"ab\" , \"fog\", \"dog\", \"car\", \"bed\"};
 Arrays.sort(str);
 System.out.println(Arrays.toString(str         


        
4条回答
  •  悲&欢浪女
    2020-11-30 11:15

    final String ORDER= "FCBWHJLOAQUXMPVINTKGZERDYS";
    
    Arrays.sort(str, new Comparator() {
    
        @Override
        public int compare(String o1, String o2) {
           return ORDER.indexOf(o1) -  ORDER.indexOf(o2) ;
        }
    });
    

    You can also add:

    o1.toUpperCase()
    

    If your array is case in-sensitive.


    Apparently the OP wants to compare not only letters but strings of letters, so it's a bit more complicated:

        public int compare(String o1, String o2) {
           int pos1 = 0;
           int pos2 = 0;
           for (int i = 0; i < Math.min(o1.length(), o2.length()) && pos1 == pos2; i++) {
              pos1 = ORDER.indexOf(o1.charAt(i));
              pos2 = ORDER.indexOf(o2.charAt(i));
           }
    
           if (pos1 == pos2 && o1.length() != o2.length()) {
               return o1.length() - o2.length();
           }
    
           return pos1  - pos2  ;
        }
    

提交回复
热议问题