Sorting an array of String with custom ordering

后端 未结 4 1441
不知归路
不知归路 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:14

    Took my time to improve on the selected answer. This is more efficient

    public static void customSort(final String order,String[] array){
    String[] alphabets={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
        String keyword=order;
        for(int g=0; g() {
    
        @Override
       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 = finalKeyword.toUpperCase().indexOf(o1.toUpperCase().charAt(i));
              pos2 = finalKeyword.toUpperCase().indexOf(o2.toUpperCase().charAt(i));
           }
    
           if (pos1 == pos2 && o1.length() != o2.length()) {
               return o1.length() - o2.length();
           }
    
           return pos1  - pos2  ;
        }
    });
    //Arrays.sort(array, Collections.reverseOrder());
    }
    

提交回复
热议问题