Sort an Array in Java

We can sort an array in Java using the sorting methods from Arrays class. 

Sorting an array of objects that implement Comparable

If we have an array of objects that implement Comparable interface, than we can use the Arrays.sort(Object[] a) method which only works with Comparable objects.


public class Test {

  public static void main(String[] args) {

    int[] array = new int[]{7, 1, 9, 2, 5};


Output: 1 2 5 7 9
Note: values of type int will be automatically converted to the corresponding Wrapper class. And since the Integer Wrapper class implements Comparable, we can sort an array of ints using the sort(Object[] a) method.

Sorting an array of objects that don’t implement Comparable

Suppose we need to sort an array of objects that don’t implement the Comparable interface. In that case, we can do that by specifying our Comparator and passing it as a second parameter to the sort(T[] a, Comparator<? super T> c) method.

In this example, we will sort an array of students based on a grade field.

public class Test {

  public static void main(String[] args) {

    Student[] students = new Student[4];

    students[0] = new Student("Megan", 7.5, 2);
    students[1] = new Student("Tom", 8.2, 3);
    students[2] = new Student("Suzan", 7.2, 1);
    students[3] = new Student("Steve", 9.1, 3);

    Arrays.sort(students, Comparator.comparing(Student::getGrade));;



class Student {

  private String name;
  private double grade;
  private int year;

  public Student(String name, double grade, int year) { = name;
    this.grade = grade;
    this.year = year;

  // Getters, setters and toString method

Output: Student{name=’Suzan’, grade=7.2, year=1} Student{name=’Megan’, grade=7.5, year=2} Student{name=’Tom’, grade=8.2, year=3} Student{name=’Steve’, grade=9.1, year=3}
That’s it!
Happy coding!

Leave a Reply

Your email address will not be published.