Best 10 Array Sort examples in Java

You can also check my previous post on array tutorials with examples Array is a collection of elements stored under a single name.

Arrays Sort Examples

Sort is based on ascending or descending order. For numbers, Ascending order means lowest number to highest number i.e Numbers in the array will be increasing in order. descending order means the highest number to the lowest number i.e. Numbers are decreasing in order.

For the Alphabet, A, B, C is a natural order and ascending order, C, B, A is the reverse of ascending and descending order.

This post is about various Best Array sort examples in Java.

Arrays. sort method Java examples

The java.util.Arrays.sort method is used to sort the primitive types as well as objects.

public static void sort(T\[\] a, Comparator c)

parameters:-

The first parameter is any object or primitive type T.

The second is Comparator: a function for comparing the values in an array. It contains logic to sort the order of the array to return.

How to Sort an Array of Numbers in ascending order?

In Java, an array can store integer and long types. The array has a sort method, which sorts and modifies the array in its natural (ascending) sorting order.

The following example demonstrates sorting an array of integers in ascending order.

import java.util.Arrays;

public class ArraySortTest {
    public static void main(String[] args) {
        Integer[] numbers = { 5,3,17,1};
        System.out.println(Arrays.toString(numbers));
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));
    }
}

Output:

Original:[5, 3, 17, 1]
Sorted asc order:[1, 3, 5, 17]

How to sort integer arrays in descending order?

The sort() method in the Array class has a Comparator parameter.

When you use the sort() method without a comparator, it arranges the elements in ascending order. If you want to sort them in descending order, you have two options: create your own comparator or use the Collections.reverseOrder()method.

To sort the array in descending order, you can use Array.sort(array, Collections.reverseOrder()), where array is the array to be sorted, and Collections.reverseOrder() is the comparator.

Following is an example

import java.util.Arrays;
import java.util.Collections;

public class ArraySortTest {
    public static void main(String[] args) {
        // Array to be sorted
        Integer[] numbers = { 5,3,17,1};
        // Print an array
        System.out.println("Original:"+Arrays.toString(numbers));
        // Sort an array in descending order
        Arrays.sort(numbers, Collections.reverseOrder());
        // Print an array
        System.out.println("Sorted desc order:"+Arrays.toString(numbers));
    }
}

Output:

Original:[5, 3, 17, 1]
Sorted desc order:[17, 5, 3, 1]

How to sort String arrays in ascending order?

String sorting is simple to do with Array.sort method. When you pass a string array to the sort method, it organizes the array in ascending (natural) order, resulting in elements being displayed in alphabetical order.

import java.util.Arrays;
import java.util.Collections;

public class ArraySortTest {
    public static void main(String[] args) {
        String[] strs = { "one", "two", "three", "four", "five","five"};
        System.out.println("Original:"+Arrays.toString(strs));
        Arrays.sort(strs);
        System.out.println("Sorted asc order:"+Arrays.toString(strs));

    }
}

Output

Original:[one, two, three, four, five, five]
Sorted asc order:[five, five, four, one, three, two]

How to sort String arrays in descending order?

To customize the default sorting order, use reverseOrder() as a comparator to the Array.sort() method to order in descending order.

import java.util.Arrays;
import java.util.Collections;

public class ArraySortTest {
    public static void main(String[] args) {
        String[] strs = { "one", "two", "three", "four", "five" ,"five"};
        System.out.println("Original:"+Arrays.toString(strs));
        Arrays.sort(strs,Collections.reverseOrder());
        System.out.println("Sorted desc order:"+Arrays.toString(strs));

    }
}

Output is

Original:[one, two, three, four, five, five]
Sorted desc order:[two, three, one, four, five, five]

How to sort a Two-dimensional array in Java?

Two-dimensional arrays are arrays that contain arrays. To sort elements in a two-dimensional array, you need to write a comparator. This approach applies to all versions of Java.

import java.util.Arrays;
import java.util.Comparator;

public class ArraySortTest {
    public static void main(String[] args) {
        int[][] arrays = { { 3, 9 }, { 2, 5 }, {18, 19 }, { 41, 3 }, { 15, 4 } };
        System.out.println("Original:"+Arrays.deepToString(arrays));
        Arrays.sort(arrays, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return ((Integer) o2[0]).compareTo(o1[0]);
            }
        });
        System.out.println("Sorted:"+Arrays.deepToString(arrays));
    }
}

The code was refactored using Java 8 streams.

import java.util.Arrays;
import java.util.Comparator;

public class ArraySortTest {
    public static void main(String[] args) {
        int[][] arrays = { { 3, 9 }, { 2, 5 }, {18, 19 }, { 41, 3 }, { 15, 4 } };
        System.out.println("Original:"+Arrays.deepToString(arrays));
        Arrays.sort(arrays, Comparator.comparing((int[] arr) -> arr[0])
                .reversed());

        System.out.println("Sorted:"+Arrays.deepToString(arrays));
    }
}

output:

[[3, 9], [2, 5], [18, 19], [41, 3], [15, 4]]
[[41, 3], [18, 19], [15, 4], [3, 9], [2, 5]]

How to sort and merge integer arrays in Java?

  • Two arrays were created with inline initialization syntax.
  • The lengths of the two arrays were added, and a new array with a size equal to the sum was created.
  • Both array objects were copied to a new array using the arrayCopy method.
  • Finally, the method sorts the new array using the Arrays.sort() method.
import java.util.Arrays;

public class ArraySortTest {
    public static void main(String[] args) {
        Integer array1[] = { 9, 5, 71 };
        Integer array2[] = { 21, 50, 1 };
        Integer output[] = new Integer[array1.length + array2.length];
        System.arraycopy(array1, 0, output, 0, array1.length);
        System.arraycopy(array2, 0, output, array1.length, array2.length);
        Arrays.sort(output);
        System.out.println(Arrays.toString(output));
    }
}
[1, 5, 9, 21, 50, 71];

How to sort Custom Object Arrays in ascending or descending order?

Let’s create an Employee class featuring id and salary fields. This class implements the Comparable interface and includes an implementation for the compareTo() method, incorporating logic for sorting fields in ascending or descending order.

The class also contains setter and getter methods for the properties, along with a toString() method for displaying details when printing an object.

 class Employee implements Comparable<Employee> {
    Integer id;
    Integer salary;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getSalary() {
        return salary;
    }
    public void setSalary(Integer salary) {
        this.salary = salary;
    }
    Employee(Integer id, Integer salary) {
        this.id = id;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", salary=" + salary + "]";
    }
    @Override
    public int compareTo(Employee o) {
         return this.salary - o.salary;
     }
 }

Sort Employees based on salary ascending order:

Array.sort() method used with an array of objects, Sorts the array in ascending order.

import java.util.Arrays;
public class ArraySortTest {
    public static void main(String[] args) {
        Employee[] emps = new Employee[3];
        emps[0] = new Employee(1, 4000);
        emps[1] = new Employee(2, 60000);
        emps[2] = new Employee(3, 5000);
        Arrays.sort(emps);
        for (int i = 0; i < emps.length; i++) {
            Employee emp = emps[i];
            System.out.println(emp);
        }
    }
}
Employee[((id = 1), (salary = 4000))];
Employee[((id = 3), (salary = 5000))];
Employee[((id = 2), (salary = 60000))];

Sort Employees based on salary descending order:

import java.util.Arrays;
import java.util.Collections;

public class ArraySortTest {
    public static void main(String[] args) {
        Employee[] emps = new Employee[3];
        emps[0] = new Employee(1, 4000);
        emps[1] = new Employee(2, 60000);
        emps[2] = new Employee(3, 5000);
        Arrays.sort(emps, Collections.reverseOrder());
        for (int i = 0; i < emps.length; i++) {
            Employee emp = emps[i];
            System.out.println(emp);
        }
    }
}

Output is

Employee[((id = 2), (salary = 60000))];
Employee[((id = 3), (salary = 5000))];
Employee[((id = 1), (salary = 4000))];

Conclusion

To summarize, Learn

  • How to sort and merge integer arrays in Java
  • How to sort Primitive types, and Custom Object Arrays in ascending or descending order