Arrays.sort() in Java with examples

Today we’ll learn about Arrays.sort() in Java.

Technically, Arrays.sort() is a very handy method in Java. It comes under java.util.Array package. Handling sort logics is easier with this method.

Implementation of Arrays.sort()

In this tutorial, the following are the subheadings:

  1. Implementing different data types – int, string, float.
  2. Sorting in descending order
  3. Subarray sorting
  4. Custom sort – user-specified criteria

Integer Array

In this example, I’ll declare an integer array ‘Ary’. Using for loop, we print the initial elements. Arrays.sort() takes in Ary as the function argument. With another for loop, the sorted array is displayed.

Automatically, the Ary.length method fetches the array length.

import java.util.Arrays;

public class Asort {
    public static void main(String[] args) {
        int[] Ary = {2, 11, 900, 432, 31, 5953, -1}; // Added a semicolon
        System.out.println("Initial array is:");
        for (int i = 0; i < Ary.length; i++) {
            System.out.print(", " + Ary[i]);
        }
        Arrays.sort(Ary);
        System.out.println("\n" + "----------------------");
        System.out.println("Sorted array: ");
        for (int i = 0; i < Ary.length; i++) {
            System.out.print(", " + Ary[i]);
        }
    }
}

 

Corresponding Output:

Output for the above code is as follows:

Initial array is:
2
11
900
432
31
5953
-1
Sorted array:
-1
2
11
31
432
900
5953

String array

In this example, I’ll declare a string array ‘Ary’. Using for loop, we print the initial strings. Arrays.sort() takes in Ary as the function argument. the string array is sort lexically. With another for loop, the sorted array is displayed.

Lexically refers to alphabetical order. The strings will arrange in alphabetical order.

Automatically, the Ary.length method fetches the array length.

import java.util.Arrays;
public class Asort{
  public static void main(String[] args){
  String[] Ary = {"Lays","Uncle Chips","Bingo","Pringles"};
  System.out.println("Initial array is:");
  for (int i=0;i<Ary.length;i++){
  System.out.print(", "+Ary[i]);
  }
  Arrays.sort(Ary);
  System.out.println("\n"+"----------------------");
  System.out.println("Sorted array: ");
  for(int i=0;i<Ary.length;i++){
  System.out.print(", "+Ary[i]);
  }
  }
}

Outcome:

The above code has the following outcome:

Initial array is:
, Lays, Uncle Chips, Bingo, Pringles
----------------------
Sorted array:
, Bingo, Lays, Pringles, Uncle Chips

Double Array

Though the code is the same except that the data type is ‘double’. Double is a high precision decimal data type.

import java.util.Arrays;
public class Asort{
  public static void main(String[] args){
  double[] Ary = {12.5,1.1,-9.4,0.0,2.0,2.1};
  System.out.println("Initial array is:");
  for (int i=0;i<Ary.length;i++){
  System.out.print(", "+Ary[i]);
  }
  Arrays.sort(Ary);
  System.out.println("\n"+"----------------------");
  System.out.println("Sorted array: ");
  for(int i=0;i<Ary.length;i++){
  System.out.print(", "+Ary[i]);
  }
  }
}

Result:

This code will give the following result:

Initial array is:
, 12.5, 1.1, -9.4, 0.0, 2.0, 2.1
---------------------- 
Sorted array: 
, -9.4, 0.0, 1.1, 2.0, 2.1, 12.5

Descending sort

Descending sort is also an implementation of Arrays.sort(). The sample code uses a string array.

import java.util.Arrays; 
import java.util.Collections; 
  
class ASort 
{ 
    public static void main(String[] args) 
    { 
        String Ary[] = {"LG", 
                        "Whirpool", 
                        "Godrej"
                       }; 
  
        // Sorts arr[] in ascending order 
        Arrays.sort(Ary); 
        System.out.printf("Ascending sort : \n%s\n\n", 
                          Arrays.toString(Ary)); 
        System.out.println("\n"+"-----------------");
        // Sorts arr[] in descending order 
        Arrays.sort(Ary, Collections.reverseOrder()); 
  
        System.out.printf("Descending sort : \n%s\n\n", 
                          Arrays.toString(Ary)); 
    } 
}

Descending to our output:

Ascending sort :
[Godrej, LG, Whirlpool]


-----------------
Descending sort :
[Whirlpool, LG, Godrej]

 

Sorting Subarrays:

Not only can we sort arrays, but also subarrays. Subarray is like the subset of the array. This can be done as follows:

import java.util.Arrays; 
  
public class ASort 
{ 
    public static void main(String[] args) 
    { 
        // Our arr contains 8 elements 
        String[] Ary = {"Lenovo","Dell","Apple","HP","IBM","Xiaomi","Redmi"}; 
  
        // Sorting the subarray from index 0 to 4
        // this will sort only {Lenovo, Dell, Apple, HP,IBM}  
        Arrays.sort(Ary, 0, 4); 
  
        System.out.printf("Sorting subarray : %s", Arrays.toString(Ary)); 
    } 
}

Above code results in the following output:

Sorting subarray : [Apple, Dell, HP, Lenovo, IBM, Xiaomi, Redmi]

Custom sorting with Array.sort()

Interestingly, the custom sort is also possible. We can define the criteria for sort as follows:

Likewise, this snippet has a few more packages and methods. Class Neighbors stores the details – door_no, name, and language. toString() method maps and prints these details.

Door_no_sort is the key ingredient, which uses comparator. Fairly, it sorts according to door_no of the neighbors.

import java.util.*; 
import java.lang.*; 
import java.io.*; 
 
class Neighbors 
{ 
    int Door_no; 
    String name, language; 

    // cool Constructor 
    public Neighbors(int Door_no, String name, 
                               String language) 
    { 
        this.Door_no = Door_no; 
        this.name = name; 
        this.language = language; 
    } 
  
 //neighbour details
    public String toString() 
    { 
        return this.Door_no + ",  " + this.name + 
                           ",  " + this.language; 
    } 
} 
  
class Door_No_Sort implements Comparator<Neighbors> 
{ 
 //custom sort logic
    public int compare(Neighbors a, Neighbors b) 
    { 
        return a.Door_no - b.Door_no; 
    } 
} 
  
// Main section 
class ASort 
{ 
    public static void main (String[] args) 
    { 
        Neighbors [] Ary = {new Neighbors(801, "Mehta uncle", "Gujrati"), 
                          new Neighbors(204, "Shirley aunty", "Tamil"), 
                          new Neighbors(607, "Pet Leo", "Bhow Bhow")}; 
  
        System.out.println("Initial Array:"); 
        for (int i=0; i<Ary.length; i++) 
            System.out.println(Ary[i]); 
  
        Arrays.sort(Ary, new Door_No_Sort()); 
  
        System.out.println("\nCustom sort by Door_no"); 
        for (int i=0; i<Ary.length; i++) 
            System.out.println(Ary[i]); 
    } 
}

Interesting code, interesting outcome:

Initial Array:
801, Mehta uncle, Gujrati
204, Shirley aunty, Tamil
607, Pet Leo, bhow bhow

Custom sort by door_no:
204, Shirley aunty, tamil
607, Pet Leo, bhow bhow
801, Mehta uncle, Gujrati

Finally, we implemented all examples with good outputs.

To learn more about Java concepts, and methods, visit the java reference link. For different sorting techniques –  How to sort array elements alphabetically in Java?Sorting comma-separated numbers in a string in Java

Leave a Reply

Your email address will not be published. Required fields are marked *