java - Sorting an array of String with custom ordering -


i have string array:

 string[] str = {"ab" , "fog", "dog", "car", "bed"};  arrays.sort(str);  system.out.println(arrays.tostring(str)); 

if use arrays.sort, output is:

 [ab, bed, car, dog, fog] 

but need implement following ordering:

fcbwhjloaquxmpvintkgzerdys

i think need implement comparator , override compare method:

 arrays.sort(str, new comparator<string>() {          @override         public int compare(string o1, string o2) {             // todo auto-generated method stub             return 0;         }     }); 

how should go solving this?

final string order= "fcbwhjloaquxmpvintkgzerdys";  arrays.sort(str, new comparator<string>() {      @override     public int compare(string o1, string o2) {        return order.indexof(o1) -  order.indexof(o2) ;     } }); 

you can add:

o1.touppercase() 

if array case in-sensitive.


apparently op wants compare not letters strings of letters, it's bit more complicated:

    public int compare(string o1, string o2) {        int pos1 = 0;        int pos2 = 0;        (int = 0; < 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  ;     } 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -