Ways to perform Java sorting by built-in methods

Java has a built-in method for sorting the elements in collections like ArrayLists, LinkedList etc. The arrays class also has a built-in method “sort” that enables sorting the arrays only.

You may sort the elements of arrays or collections in ascending or descending order. In this tutorial, I will show you how to use the Java array sort method along with java.util.collections.sort method for ArrayList and other collections and bubbleSort algorithm(in the last section), so keep reading.

Java array sort method

First, let me start with the array sort method. You may skip to next section for learning about the Collections sort method.

The method for sorting arrays belongs to java.util.Arrays.sort(). The sort method of arrays does not return any value but simply sorts the given array in ascending order. You may use the sort method of arrays for sorting the numeric or string arrays.

Syntax of using the sort method in Arrays

Following is the general syntax of using the sort method of arrays class:

public static void sort(array_to_sort)

In this way, the given array elements will be sorted into ascending numerical order. The method returns no value.

You may also specify the selection of elements to sort in the given array as follows:

public static void sort(array,

        int fromIndex,

        int toIndex)

In that way:

  • The array argument is the array you want to sort. This can be a primitive type like int, float, byte etc. or objects.
  • The fromIndex parameter specifies the starting index position (inclusive).
  • While the toindex specifies the end index in the given array (non-inclusive).
  • The elements will be sorted in ascending order for the given range.
Note: For sorting the elements in descending order, see the example number 2 and 3 below.

An example of sorting an int array

For sorting arrays demo, an array of int elements is created in random order. After that, the sort Java method is used for sorting the elements in ascending order. For seeing the difference, the array elements before and after using the sort method are displayed:

import java.util.Arrays;



public class sort_demo {

           public static void main(String[] args) {

          

               int[] arr_int = {5,3,7,1,11,9};

              

               System.out.println("Array before sorting: " + Arrays.toString(arr_int)+"\n");

               Arrays.sort(arr_int);

               System.out.println("Array after sorting: " + Arrays.toString(arr_int));

           }

}

Output:

sort int array Java

Demo of sorting elements in descending order

For sorting the arrays in descending order you may use the arrays.sort() method with the Collections.reverseOrder() method. However, the reverseOrder() method works with objects only. So, if you have a primitive type array like in above example, it will not work.

For this example, an array of Integer type is created that contains random numbers. After that, sort method with reverseOrder() is used for sorting in descending order:

import java.util.Arrays;

import java.util.Collections;



public class sort_demo {

                    public static void main(String[] args) {

                   

                        Integer[] arr_integer = {55,11,44,99,60,65};

                       

                        System.out.println("Array before sorting: " + Arrays.toString(arr_integer)+"\n");



                        Arrays.sort(arr_integer, Collections.reverseOrder());

                        System.out.println("Array in DESC order: " + Arrays.toString(arr_integer));

                    }

}

sort int array DESC

Sort a string array example

Similarly, you may sort a string array that contains string elements in random order. For sorting a string array example, I created an array with alphabets in random order.

The Java array sort method is used twice:

  • First for sorting string elements in ascending order
  • The second uses Collections.reverseOrder() method with sort() for descending order

Have a look:

import java.util.Arrays;

import java.util.Collections;



public class sort_demo {

           public static void main(String[] args)

           {

               String arr_string[] = {"c","d", "a", "e","k","z", "l", "b"

                              };



               System.out.println("Original string array: " + Arrays.toString(arr_string)+"\n");              



               //sort in ASC order

               Arrays.sort(arr_string);

               System.out.println("String array in Asc: " + Arrays.toString(arr_string)+"\n");



               //sort in DESC order

               Arrays.sort(arr_string, Collections.reverseOrder());

               System.out.println("String Array in DESC order: " + Arrays.toString(arr_string));



           }

}

Output:

Java array sort

Note: Do not forget to import java.util.Collections in order to sort in descending order for arrays.

Sorting a selection of array elements example

As mentioned earlier, the array sort method also allows sorting the given range of array elements. For example, you only need to sort the elements from 3 to 7 index positions.

import java.util.Arrays;



public class sort_demo {

           public static void main(String[] args) {

          

               int[] arr_int = {15,13,17,11,19,21, 3, 7, 5};

              

               System.out.println("Original int array: " + Arrays.toString(arr_int)+"\n");

               Arrays.sort(arr_int,2,7);

               System.out.println("Array range sorting: " + Arrays.toString(arr_int));

           }

}

The output of above code is:

Original int array: [15, 13, 17, 11, 19, 21, 3, 7, 5]

Array range sorting: [15, 13, 3, 11, 17, 19, 21, 7, 5]

You can see, the elements 0 and 1 remained in the same place even after using the sort() method. The sorting started at index 2 and ended at 6 position. The reason is endindex parameter does not include the given number.

A simple solution for primitive type descending order

As mentioned earlier, the primitive type array cannot be sorted in descending order by using the Collections.reverseOrder() method. You may develop your own algorithm or use some other class by the third party if this is really required.

Following is a simple solution that you may use for primitive type array in descending order.

import java.util.Arrays;



public class sort_demo {

           public static void main(String[] args) {

          

               int[] arr_int = {7,3,13,15,5,21,-1};

              

               System.out.println("Array before sorting: " + Arrays.toString(arr_int)+"\n");

               Arrays.sort(arr_int);

               System.out.println("Array after sorting: " + Arrays.toString(arr_int)+"\n");



               System.out.println("In descending order:");

               for(int i=arr_int.length-1; i>=0; i--) {

                   System.out.println(arr_int[i]);

               }

              

           }

}

The output of this program:

Array before sorting: [7, 3, 13, 15, 5, 21, -1]

 

Array after sorting: [-1, 3, 5, 7, 13, 15, 21]

 

In descending order:

21

15

13

7

5

3

-1

You see, the int array is displayed in original order, in ascending order by using sort() method and finally in descending order.

Java Collections sort method

Now, let us explore the Collections sort method that enables list sort like ArrayList, LinkedList etc. The array sort method allows sorting only the elements of the array. However, you may use the Collections sort method for sorting different collections.

Syntax of using the Collections sort method

Following is the syntax for using the Collections.sort method:

sort(List<T> list)

Where:

  • List argument can be ArrayList, LinkedList etc.
  • The list sorting is in ascending order.
  • This method does not return any value.
  • The collection sort method can only be used for sorting objects, unlike the arrays sort where primitive type can also be sorted.
  • You may use the reverseOrder() method for ordering a list in descending order.

You may also use list sort method as follows:

sort(List<T> list, Comparator<? super T> c)

In this way, the list is sorted based on the specified comparator.

An example of sorting ArrayList items

For demonstrating the sort method of Collections, an ArrayList of 5 elements that are vowel letters is created in random order. After that, the sort method is used for ordering it in ascending order as follows:

import java.util.*;



public class sort_demo {

           public static void main(String[] args) {

          

               ArrayList<String> vowel_list_sort = new ArrayList<String>(); //Declaring vowel ArrayList



               vowel_list_sort.add("a");

               vowel_list_sort.add("u");

               vowel_list_sort.add("o");

               vowel_list_sort.add("e");

               vowel_list_sort.add("i");

        

               //Displaying ArrayList

               System.out.println("Before List sort" +vowel_list_sort+"\n");

              

               //Sorting List

               Collections.sort(vowel_list_sort);

               System.out.println("After List sort" +vowel_list_sort);

           }

}

sort ArrayList Java

You can see the difference before and after using the sort method.

Example of Integer Array List sorting

For this example, the ArrayList of Integer objects is created in random order. The List is displayed before and after using the sort Collections method:

import java.util.*;



public class sort_demo {

           public static void main(String[] args) {

          

               ArrayList<Integer> ranList = new ArrayList<Integer>(); //Declaring ArrayList



               ranList.add(75);

               ranList.add(11);

               ranList.add(39);

               ranList.add(7);

        

               //Displaying ArrayList

               System.out.println("Before ArrayList sort " +ranList+"\n");

              

               //Sorting ArrayList

               Collections.sort(ranList);

               System.out.println("After ArrayList sort " +ranList);

           }

}

sort ArrayList integer

Sorting string ArrayList in descending order example

The sorting of the list is done in ascending order as using the sort method. If you require getting the list in descending order then you may use the reverseOrder() method of Collections.

The following example shows a string list sorted in descending order:

import java.util.*;



public class sort_demo {

           public static void main(String[] args) {

          

               ArrayList<String> vow_list = new ArrayList<String>(); //Declaring vowel ArrayList



               vow_list.add("a");

               vow_list.add("u");

               vow_list.add("o");

               vow_list.add("e");

               vow_list.add("i");

        

               //Displaying ArrayList

               System.out.println("Original List " +vow_list+"\n");

              

               //Sorting List

               Collections.sort(vow_list);

               System.out.println("Sorted list in Ascending Order " +vow_list +"\n");

              

               //In desc order

               Collections.sort(vow_list, Collections.reverseOrder());

               System.out.println("Sorted list in Descending Order " +vow_list);

           }

}

The output of above example is:

Original List [a, u, o, e, i]

 

Sorted list in Ascending Order [a, e, i, o, u]

 

Sorted list in Descending Order [u, o, i, e, a]

Did you notice, this is the other way of using the Java Collections.sort method described in the syntax section? That is:

Collections.sort(List<T> list, Comparator<? super T> c)

Using  Collections reverse method for descending order

You may also use the reverse method of Collections for sorting the list in descending order. This is how you may use it:

Collections.reverse(list);

See an example below for making things clearer:

import java.util.*;



public class sort_demo {

           public static void main(String[] args) {

          

               ArrayList<Integer> intList = new ArrayList<Integer>(); //Declaring ArrayList



               intList.add(20);

               intList.add(5);

               intList.add(10);

               intList.add(25);

               intList.add(15);



        

               //Displaying ArrayList

               System.out.println("Original List " +intList+"\n");

              

               //Sorting List

               Collections.sort(intList);

               System.out.println("Sorted Integer list in Ascending Order " +intList +"\n");

              

               //In desc order

               Collections.reverse(intList);

               System.out.println("Sorted Integer list in Descending Order " +intList);

           }

}

The output:

Original List [20, 5, 10, 25, 15]

 

Sorted list in Ascending Order [5, 10, 15, 20, 25]

 

Sorted list in Descending Order [25, 20, 15, 10, 5]

Is not that even cool?

Using bubble sort Algorithm for sorting arrays

You may also use the Bubble sort algo for sorting the arrays. The bubble sort algorithm swaps the elements one by one and if this element is greater than the next then it is swapped. The process goes on until all elements in the given array are entertained.

See the following example where you can see Bubble sort algorithm code along with an example array that is passed for sorting.

import java.util.*;



public class sort_demo { 

    static void bubbleSort(int[] arr_sort) { 

        int num = arr_sort.length; 

        int z = 0; 

         for(int x=0; x < num; x++){ 

           for(int y=1; y < (num-x); y++){ 

              if(arr_sort[y-1] > arr_sort[y]){ 

                z = arr_sort[y-1]; 

                arr_sort[y-1] = arr_sort[y]; 

                arr_sort[y] = z; 

               } 

                         

             } 

        } 

    }

         public static void main(String[] args) { 

               int[] arr_int = {47,13,9,19,5,1,-1,-11};

              

               System.out.println("Array before Bubble sorting: " + Arrays.toString(arr_int)+"\n");

              bubbleSort(arr_int);

               System.out.println("Array after Bubble sorting: " + Arrays.toString(arr_int));





     } 

}

The output:

Array before Bubble sorting: [47, 13, 9, 19, 5, 1, -1, -11]

 

Array after Bubble sorting: [-11, -1, 1, 5, 9, 13, 19, 47]

The array is sorted in ascending order.

Note: The above solution applies to the primitive int and Integer based arrays.

Demo of sorting double array by Java Bubble sort algorithm

The above algorithm requires a little tweak for enabling double array sorting. See the example below where an array with double elements is created and passed to bubbleSort algo. Look carefully in the first part to see the difference between two algorithms:

import java.util.*;



public class sort_demo { 

    static void bubbleSort(double[] arr_sort) { 

        int num = arr_sort.length; 

        double z = 0; 

         for(int x=0; x < num; x++){ 

           for(int y=1; y < (num-x); y++){ 

              if(arr_sort[y-1] > arr_sort[y]){ 

                z = arr_sort[y-1]; 

                arr_sort[y-1] = arr_sort[y]; 

                arr_sort[y] = z; 

               } 

                         

             } 

        } 

    }

         public static void main(String[] args) { 

               double[] arr_double = {1.5,9.5,19.5,5,1.8,-1.4,-11.5};

              

               System.out.println("double array before Bubble sorting: " + Arrays.toString(arr_double)+"\n");

              bubbleSort(arr_double);

               System.out.println("double array after Bubble sorting: " + Arrays.toString(arr_double));





     } 

}

The Output:

double array before Bubble sorting: [1.5, 9.5, 19.5, 5.0, 1.8, -1.4, -11.5]

 

double array after Bubble sorting: [-11.5, -1.4, 1.5, 1.8, 5.0, 9.5, 19.5]

Likewise, you may use the Double and Integer etc/ objects sorting as using the bubble sort solution.

Summarizing the sorting in Java

Java has a few methods for sorting the elements of arrays and collections in ascending and descending order.

  • The Java arrays sort method is for sorting array elements in ascending order. This method can be used for a primitive type like int, float, etc as well as object arrays.
  • Similarly, the Collections has a built-in method “sort()” that is used for sorting the Lists. For example, ArrayList, LinkedList, etc. The Collections.sort() method also sorts elements in ascending order.
  • For descending order of arrays and collections elements, you may use the reverse() and reverseOrder() methods of Collections.
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!