Sort array first by length then alphabetically in Java

16,502

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

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.

Share:
16,502
Brian
Author by

Brian

Updated on June 09, 2022

Comments

  • Brian
    Brian almost 2 years

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

    I 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

  • Mark Peters
    Mark Peters over 13 years
    Also note the existence of compareToIgnoreCase().
  • Starkey
    Starkey over 13 years
    Comparator requires int compareTo(Obj o), not compare(Object o1, Object o2). This code is close though.
  • Mark Peters
    Mark Peters over 13 years
    @Starkey: That's Comparable. This is Comparator. You were close though.
  • Brian
    Brian over 13 years
    Thanks, I just needed to sort some file names that had numbers in them really quickly and rename them. I had them in an Array so I had to convert it to a Collection, but this worked for my purpose. Thanks!
  • Markus Schober
    Markus Schober over 13 years
    @Mark Peters What about Comparatee?
  • Maytham Fahmi
    Maytham Fahmi over 8 years
    nice way of sorting + @KeatsPeeks