Java Collection How to - Sort array with customized Comparator








Question

We would like to know how to sort array with customized Comparator.

Answer

import java.util.Arrays;
import java.util.Comparator;
/*from w  w  w .j av  a 2  s  . c  o m*/
public class Main {
  public static void main(String[] args) {
    String[] strings = { "Here", "are", "some", "sample", "strings", "to",
        "be", "sorted" };

    Arrays.sort(strings, new Comparator<String>() {
      public int compare(String s1, String s2) {
        int c = s2.length() - s1.length();
        if (c == 0)
          c = s1.compareToIgnoreCase(s2);
        return c;
      }
    });

    for (String s : strings)
      System.out.print(s + " ");
  }
}

The code above generates the following result.