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:
Post a Comment