Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of String with custom ordering

Tags:

java

arrays

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?

like image 231
Hamid Avatar asked May 14 '13 10:05

Hamid


1 Answers

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  ;
    }
like image 191
Majid Laissi Avatar answered Oct 03 '22 11:10

Majid Laissi