Sorting an array alphabetically

java

Solution

You need a custom `Comparator` for that using `Arrays.sort()`:

Arrays.sort(array, new CustomComparator());

public class CustomComparator implements Comparator<String> {
  private final Pattern pattern = Pattern.compile("(\\d+)\\s+(.*)");

  public int compare(String s1, String s2) {
    Matcher m1 = pattern.matcher(s1);
    if (!m1.matches()) {
      throw new IllegalArgumentException("s1 doesn't match: " + s1);
    }
    Matcher m2 = pattern.matcher(s2);
    if (!m2.matches()) {
      throw new IllegalArgumentException("s2 doesn't match: " + s2);
    }
    int i1 = Integer.parseInt(m1.group(1));
    int i2 = Integer.parseInt(m2.group(1));
    if (i1 < i2) {
      return 1;
    } else if (i1 > i2) {
      return -1;
    }
    return m1.group(2).compareTo(m2.group(2));
  }
}

For `Collections` you can use `Collections.sort()`

The above assumes your array elements are `String`s like `"22 ASomething"` rather than a specific data structure containing occurrences and some text. If that is the case you can use a simpler `Comparator`.

Also if you do have an array of `String`s it might be worth first transforming it into an array of objects that have been parsed to save over-parsing the elements (ie some elements will be parsed more than once).

Problem

I have an array which i need to sort its elements by occurrence then alphabetically. For example: ``` 55 The 32 ASomething 32 BSomething ASomething should come before Bsomething because: 1) they have the same number 2) A comes before B alphabetically ``` So you sort first by the number of occurrence then Alphabetically What is the best way to do that. I am using merge sort to sort the counts but how do I put a statement that it will check if they have the same number, it sorts alphabetically (could be more than 2 words). SOLUTION: What I did is a merge sort on the data before I did a merge sorts on the counts of data and that was good enough :) Thanks everyone for the help

Original source