Sort array in alphabetical order

I have an array that I need to sort by its elements and then alphabetically. For instance:

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 occurrences, then alphabetically

What is the best way to do this. I use merge sort to sort counters, but how can I put an operator to check if it has the same number, it is sorted alphabetically (maybe more than two words).

SOLUTION: what I did was sort the data merge before I did the merge sort by data counts, and that was good enough. Thank you all for your help.

+3
source share
2 answers

For this you will need Comparatorusing 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));
  }
}

Collections Collections.sort()

, String "22 ASomething", , . , Comparator.

, String, , (.. ).

+4

, , , "", java.util.Collections.sort:

: .

, , . , Map > , , . .

0

Source: https://habr.com/ru/post/1735355/


All Articles