Friday, December 18, 2009

Custom String Length Comparator Java

The default sort method for strings is Java is it's character values. For example, If we have a string array:



String [] strs = {"abc", "xyz", "mnop123"};
And we use Arrays.sort(strs), the output will be in the following order:


abc
mnop123
xyz
But there are times, when we want to sort strings, by their length. The following custom string length comparator will serve the purpose:


import java.util.Comparator;

public class CustomStringLengthComparator implements Comparator{

 public int compare(String o1, String o2) {
  if (o1.length() < o2.length()) {
        return -1;
      } else if (o1.length() > o2.length()) {
        return 1;
      } else {
        return 0;
      }
 }

}


Instead of using


Arrays.sort(strs)
we have to use


Arrays.sort(strs, new CustomStringLengthComparator());



No comments: