I have a String array:
 String[] str = {"ab" , "fog", "dog", "car", "bed"};
 Arrays.sort(str);
 System.out.println(Arrays.toString(str));
If I use Arrays.sort, the output is:
 [ab, bed, car, dog, fog]
But I need to implement the following ordering:
FCBWHJLOAQUXMPVINTKGZERDYS
I think I need to implement Comparator and 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 I go about 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 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  ;
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With