Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array first by length then alphabetically in Java

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

like image 833
Brian Avatar asked Aug 04 '10 19:08

Brian


3 Answers

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());
like image 71
KeatsPeeks Avatar answered Oct 24 '22 04:10

KeatsPeeks


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));
like image 30
Lukas Eder Avatar answered Oct 24 '22 02:10

Lukas Eder


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

like image 4
Peter Lawrey Avatar answered Oct 24 '22 03:10

Peter Lawrey