开发者

Sort array first by length then alphabetically in Java

How can I sort an array first by length, then alphabetically?

开发者_如何学CI have a list of things with numbers on them, and I am currently getting:

Something1 Something10 Something2 Something3

Whereas I want to get:

Something1 Something2 Something3 Something10


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());


Here's a concise Java 8 solution:

List<String> list = Arrays.asList("Something1", "Something10", "Something2", "Something3");
list.sort(Comparator.comparing(String::length).thenComparing(String::compareTo));

Or, case-insensitive version:

list.sort(Comparator.comparing(String::length).thenComparing(String::compareToIgnoreCase));


Create a Comparator which compares by length first and if the lengths are the same, uses the String.compareTo().


Sorting first by length and then lexically will work ONLY if the string prefixes (i.e. the part before the number) is the same length in all cases. I believe you may really want to write a comparator that separates the string and numeric parts and sorts alphabetically on the string and numerically on the number part.


Define a class to hold your item in. Seems like you want it to be a String.

For that class, you need to define the Comparable interface and put the logic to compare in its abstract method.

int compareTo(T o)  

For example:

class MyString extends String
{
  @Override
  int compareTo(Object obj)
  {
    // put your logic in here. 
    // Return -1 if this is "less than" obj. 
    // Return 0 if this is equal to obj
    // Return 1 if this is "greater than" obj.

    // Test length first
    if (length() < obj.length())
      return -1;
    if (length() > obj.length())
      return 1;

    // Lengths are the same, use the alphabetical compare defined by String already
    return super.compareTo(obj);
   }
}

Disclaimer, I didn't actually test this code, but it should be close to what you want.


By using lambda, The java program looking like.

import java.util.Arrays;
import java.util.List;

public class Test1 {

    public static void main(String[] args) {
        
        String str = "This is am example";
        List<String> strl = Arrays.asList(str.split(" "));
        strl.sort( (o1,o2)->{
            if(o1.length() > o2.length())      return 1;
            else if(o1.length() < o2.length()) return -1;
            else                               return o1.compareTo(o2);
        });
        System.out.println(strl);

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜