Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to sort an array

Short answer

Arrays.sort() sorts the array in place in ascending order:

void main() {
    int[] numbers = {10, 9, 1, 100};
    Arrays.sort(numbers);
 
    IO.println(Arrays.toString(numbers));
}

Output:

[1, 9, 10, 100]

Descending order

A comparator works only with objects, so the array must be Integer[], not int[]:

void main() {
    Integer[] numbers = {10, 9, 1, 100};
    Arrays.sort(numbers, Comparator.reverseOrder());
 
    IO.println(Arrays.toString(numbers));
}

Output:

[100, 10, 9, 1]

Strings

Strings are sorted by character codes — capitals come before lower case letters. There is a ready comparator for case-insensitive sorting:

void main() {
    String[] words = {"pear", "apple", "Banana"};
 
    Arrays.sort(words);
    IO.println(Arrays.toString(words));
 
    Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);
    IO.println(Arrays.toString(words));
}

Output:

[Banana, apple, pear]
[apple, Banana, pear]

By an object field

Comparator.comparing() creates a comparator from a field value:

record User(String name, int age) {}
 
void main() {
    User[] users = {new User("Anna", 30), new User("Oleg", 25)};
    Arrays.sort(users, Comparator.comparing(User::age));
 
    IO.println(Arrays.toString(users));
}

Output:

[User[name=Oleg, age=25], User[name=Anna, age=30]]

Keeping the original array

Arrays.sort() changes the array itself. To keep the original order, sort a copy:

void main() {
    int[] numbers = {3, 1, 2};
    int[] sorted = numbers.clone();
    Arrays.sort(sorted);
 
    IO.println(Arrays.toString(numbers));
    IO.println(Arrays.toString(sorted));
}

Output:

[3, 1, 2]
[1, 2, 3]

Common mistake

Passing a comparator together with an int[]. There is no such method for primitive arrays:

void main() {
    int[] numbers = {3, 1, 2};
    Arrays.sort(numbers, Comparator.reverseOrder());
}

Output:

Main.java:3: error: no suitable method found for sort(int[],Comparator<T#1>)

Use Integer[], or sort in ascending order and walk the array from the end.

Functions used in this recipe

  • Arrays.sort() — Sorts an array in place — in ascending order or by a given comparator.
  • Comparator.reversed() — Returns a comparator with the opposite order. For the natural order there is Comparator.reverseOrder().
  • Comparator.comparing() — Creates a comparator that compares objects by one key.

Thanks for reading!

Donate to the site — we work hard for you.