An example to overwrite comparator in method to customize sorting of array

I still feel confused when I want to customize the way of sorting for array and collections in java. And here is a good example of how to write a customized sorting function to sort string array:

    Comparator<String> comp = new Comparator<String>(){
            @Override
            public int compare(String str1, String str2){
                String s1 = str1 + str2;
                String s2 = str2 + str1;
                return s2.compareTo(s1); // reverse order here, so we can do append() later
            }
         };

        Arrays.sort(s_num, comp);

Leave a Reply