Sort the array by length, then alphabetically

How do I arrange arrays alphabetically?

I have a list of numbers that I'm getting:

Something1 Something10 Something2 Something3

And I want to get:

Thing 1 thing 2 thing 10

Solution

public class MyComparator implements Comparator<String>{
public class MyComparator implements Comparator<String>{
    @Override
    public int compare(String o1,String o2) {  
      if (o1.length() > o2.length()) {
         return 1;
      } else if (o1.length() < o2.length()) {
         return -1;
      }
      return o1.compareTo(o2);
    }
}

Then use:

Collections.sort(yourList,new MyComparator());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>