Guide to Sorting in Java

September 09, 2022
Sorting In Java



Sorting in Java

Sorting is quite a common feature in every programming language. Sorting in Java refers to arranging the objects in ascending, descending or any particular order. Java offers various predefined methods that can be used to sort arrays, Lists, Sets and Maps in Java.

In this article, we will be exploring the different methods to sort data in Java and how they can be implemented in your Java code.

new java job roles

Arrays.Sort() Method

Java offers the Arrays.sort() method for sorting an array of objects of primitive data types. It is defined in the java.util.Arrays package. The return type of this method is void as it does not return any value. It also uses the most efficient sorting algorithm depending on the content of the array. For instance, the array of objects will be sorted using merge sort, while the array containing primitive datatypes is sorted with quicksort.

Following is the syntax for using arrays.sort() method where an array, myArr is passed as a parameter to be sorted:

public static void sort(Object[ ] myArr)

The above-mentioned method is used to sort the complete array but it can also be overloaded to sort a specific part of an array,

See this overloaded method below:

public static void sort(Object[ ] myArr, int start, int end)

Again, the myArr specifies the array to be sorted. The start parameter indicates the starting index from which sorting is to be started, and the end parameter specifies the index value up to which perform sorting will be performed, excluding the end value. The start and end parameters are only provided when you just want the subarray to get sorted.

See this example below demonstrating the sorting of a string array in ascending and descending order using arrays.sort():

1. import java.util.Arrays;
2. import java.util.Collections;
3.   class ArrSorting {
4.   public static void main(String[] args) {
5.   // creating a string array
6.   String[] fruits = { "apple", "kiwi", "peach", "grapes", "banana" };
7.   System.out.print("Unsorted Array: ");
8.   for (String a : fruits)
9.   System.out.print(a + " ");
10.  // sorting the array in ascending order
11.  Arrays.sort(fruits);
12.  System.out.print("nArray sorted in Ascending order: ");
13.  for (String a : fruits)
14.  System.out.print(a + " ");
15.  // sorting in descending order is done using the Collections.reverseOrder()
16.  Arrays.sort(fruits, Collections.reverseOrder());
17.  System.out.print("nArray sorted in Descending order: ");
18.   for (String a : fruits)
19.   System.out.print(a + " ");
20.   System.out.println();
21. }
22. }

See the following output:

Unsorted Array: apple kiwi peach grapes banana

Array sorted in Descending order: apple banana grapes kiwi peach 

Array sorted in Ascending order: peach kiwi grapes banana apple

In this example, the overloaded Arrays.sort(array[], start, end) is now used to sort a part of an Array:

1. public void usingOverloadedSortMethod() {
2.   Arrays.sort(fruits, 2, 4);
3.   for (String a : fruits)
4.   System.out.print(a + " ");
5.   System.out.println(); 
6. }

The sorting will be done only on the following sub-array elements (toIndex would be exclusive):

[“peach”, “grapes”, “banana”]

The resultant sorted sub-array with the complete array would be like this where only element from 2 to 4 are sorted leaving the first two elements as it is:

["apple", "kiwi", "banana", "grapes","peach"]

Following is the list of overloading options for the Array.sort() method that offers to sort a variety of different types of data or objects in Arrays:

public static void sort(byte[] arr, int start, int end)

public static void sort(byte[] arr)

public static void sort(short[] arr, int start, int end)

public static void sort(short[] arr)

public static void sort(int[] arr, int start, int end)

public static void sort(int[] arr)

public static void sort(long[] arr, int start, int end)

public static void sort(long[] arr)

public static void sort(double[] arr, int start, int end)

public static void sort(double[] arr)

public static void sort(float[] arr, int start, int end)

public static void sort(float[] arr)

public static void sort(char[] arr, int start, int end)

public static void sort(char[] arr)

public static void sort(String[] arr, int start, int end)

public static void sort(String[] arr)

Collection.sort() Method

Another approach for sorting in Java is using the Collections.sort() method. This method is defined in the java.util.Collections package. It is commonly used to sort the List collections such as LinkedList, Queue or ArrayList etc. It is used to sort the elements present in the specified list of Collections in ascending order. This is a void method and does not return anything. It works quite similar to the java.util.Arrays.sort() method but it can also sort the elements in a linked list, arraylist, queue and various other list collections which cannot be done with Arrays.sort().

See the syntax for collection.sort() below where mylist is the List type object to sorted:

public static void sort(List mylist)

See the following example code where an ArrayList is sorted using the Collections.sort() method:

import java.util.*;

class ListSorting {

  public static void main(String[] args) {

    // Creating an integer type arraylist to be sorted

    ArrayList<Integer> myList = new ArrayList<Integer>();

    arr.add(23);

    arr.add(8);

    arr.add(14);

    arr.add(19);

    arr.add(42);

    System.out.println("Unsorted ArrayList: " + myList);

    // sorting the arraylist

    Collections.sort(myList);

    System.out.println("Sorted ArrayList: " + myList);

  }

}

The output will be:

Unsorted ArrayList: [23, 8, 14, 19, 42]

Sorted ArrayList: [8, 14, 19, 23, 42]

Sorting Custom Objects

We have discussed how to sort an array or a list collection but sorting a custom object in Java requires a different technique.

An array of custom objects is created in the example below, we will be referring to it in the later examples of sorting custom objects:

public class Student implements Comparable {

    private String name;

    private int age;

    public Student(String name, int age) {

      ...

// getters and setters

    }   

}

Now let’s create an array of objects for the Student class:

public void objectSorting () {

    ....    

    students = new Student[] { 

      new Student("Jim", 15), new Student("Sarah", 17), 

      new Student("Flynn", 19), new Student("Erin", 13), 

      new Student("Jake", 14), new Student("Pam", 16)};

}

}

As arrays or collections of custom objects contains various values to be sorted, there are two ways to sort objects in Java,

1. The Comparable Interface

Java Comparable interface is used to order the custom objects. It is found in java.lang package and offers only one method, compareTo(Object). It provides a single sorting sequence which allows sorting the elements in natural order based on a single data member from the objects. For instance, names, age, ID etc. The natural order in java is defined as the order in which objects should be orderly sorted in a given array or collection.

CompareTo(Object)

The syntax of the compareTo () function is as follows,

public int compareTo(Object obj)

This method is used to compare the current object with a specified object passed as a parameter.

It can return,

  • a positive integer, if the current object is greater than the specified object.
  • a negative integer, if the current object is less than the specified object.
  • zero, if the current object is equal to the specified object.
public class Student implements Comparable {

    ...

    @Override

    public int compareTo(Object obj1) {

        Employee s = (Student) obj;

        return getAge().compareTo(s.getAge());

    }

}

Here we are comparing the age of students. Now, when Arrays.sort(students) will be called after the above code, we now know what is the logic and order which goes into sorting the students as per the age.

2. Using the Comparator Interface

Java Comparator interface is quite similar to the Comparable interface but it is used for sorting the objects in alternative orders whereas the Comparable interface sorts by the natural order.

See this example below, using a Comparator interface implementation where an anonymous inner class is passed in the Arrays.sort() method:

public void usingComparator() {

    Integer [] integers = ArrayUtils.toObject(toSort);

    Arrays.sort(integers, new Comparator<Integer>() {

        @Override

        public int compare(Integer x, Integer y) {

            return Integer.compare(x, y);

        }

    });

    assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts)));

}

Now the students will be compared based on their age and passed in another comparator implementation:

Arrays.sort(students, new Comparator<Student>() {

    @Override

    public int compare(Student std1, Student std2) {

       return Double.compare(std1.getAge(), std2.getAge());

    }

 });

The sorted Students array will be then sorted according to age.

Sorting With Lambdas using Comparator interface

Introduced in Java 8, Lambdas can be used to implement the Comparator Functional Interface.

The comparator can be replaced with the equivalent implementation using the Lambda expression:

Comparator<Integer> c = new Comparator<>() {

    @Override

    public int compare(Integer a, Integer b) {

        return Integer.compare(a, b);

    }

}
Comparator<Integer> c = (a, b) -> Integer.compare(a, b);

The use of Lambda can make your code much more concise and cleaner.

Wrapping it up

In conclusion, Java offers tons of remarkable options to sort your objects, collections or primitive data. In this article, we have discussed different interfaces and methods to sort data and objects in Java. We also explored different ways to sort data structures and collections such as Arrays and list collections. We also covered the use of comparator and comparable interfaces for custom sorting and lastly, we briefly discussed some features of Java 8 such as Lambdas that can be useful in sorting.

Also Read: Using Java Streams In Java 8 With Examples

new Java jobs



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US