Arrays.sort() in Java with Examples
Arrays sort() method is used for sorting the elements in an Array. It consists of two variations, one in which it sorts the entire array, it may be an integer or character array. Another one allows sorting a specific part of the array by passing the starting and ending indices.
Below is a simple example that uses the sort()
method to arrange an array of integers in ascending order.
// Java Program to Implement sort()
import java.util.Arrays;
class GFG {
public static void main(String args[]) {
// Integer Array
int[] a = { 2, -1, 3, 4 };
// Character Array
char[] b = { 'b', 'a', 'c', 'b' };
// Sort both arrays
Arrays.sort(a);
Arrays.sort(b);
// Print sorted integer array
System.out.print("");
for (int n : a) {
System.out.print(n + " ");
}
// Print sorted character array
System.out.print("\n");
for (char c : b) {
System.out.print(c + " ");
}
}
}
Output
-1 2 3 4 a b b c
Explanation: In this example, we sorts the integer array and a character array using Arrays.sort(). Then it prints both arrays in ascending order. The character “b"
repeats in the output because it appears twice in the original array. Sorting does not remove duplicates, it only reorders elements.
Note: When we sorting an array of primitive types, Arrays.sort() does not allow us to provide a custom comparator. We can sort primitive types in natural order or increasing order, or non-decreasing order.
Table of Content
Syntax of Arrays.sort() method
1. sort() Method
Arrays.sort();
2. Overloaded sort() Method
public static void sort(int[] arr, int from_Index, int to_Index) ;
Parameters:
- arr: The array to be sorted.
- from_Index: The index of the first element (inclusive) to be sorted.
- to_Index: The index of the last element (exclusive) to be sorted.
Return Type:
- void (This method does not return anything).
Sorting a Subarray of an Array
To sort a specific subarray, we can use Arrays.sort() method. We have to specify a range of indices by leaving other elements of the array unchanged.
// Java program to Sort a Subarray in Array
// Using Arrays.sort() method
import java.util.Arrays;
public class GFG {
public static void main(String[] args){
int[] a = { 2, -1, 4, 3};
// Sort subarray from index 1 to 3 inclusively
Arrays.sort(a, 1, 4);
System.out.println(Arrays.toString(a));
}
}
Output
[2, -1, 3, 4]
Explanation: This example sort the elements at indices 1, 2, and 3 (-1, 4, 3) while keeping index 0 element (2) unchanged.
Sorting an Array in Descending Order Using the Reverse Order
To sort an array in descending order, we can use Arrays.sort()
method
with Collections.reverseOrder()
as a comparator.
// Java program to Sort an array in Descending order
import java.util.Arrays;
import java.util.Collections;
public class GFG {
public static void main(String[] args){
Integer[] a = { 2, -1, 3, 4};
// Sort the array in descending order using
// reverseOrder() method of Collections class
Arrays.sort(a, Collections.reverseOrder());
System.out.println(Arrays.toString(a));
}
}
Output
[4, 3, 2, -1]
Explanation: This program sorts an array of integers in descending order using Arrays.sort()
with Collections.reverseOrder()
. It works on an Integer[]
array (not int[]
). Because, the sorting requires objects not primitive types.
Sorting an Array of Strings in Descending Alphabetical Order
To sort an array of strings in descending alphabetical order, the Arrays.sort()
method
combined with Collections.reverseOrder()
method
and it arranges the strings from Z to A based on lexicographical order.
// Java program to sort an array of strings
// in descending alphabetical order
import java.util.Arrays;
import java.util.Collections;
public class GFG {
public static void main(String[] args){
// Custom input string
String a[] = { "practice.geeksforgeeks.org",
"www.geeksforgeeks.org",
"code.geeksforgeeks.org" };
// Sorts array in descending order
Arrays.sort(a, Collections.reverseOrder());
System.out.println(Arrays.toString(a));
}
}
Output
[www.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]
Sorting an Array of Objects Using a Custom Comparator
We can sort an array of objects by defining custom sorting logic with the help of using the Comparator interface.
// Java program to sort an array using custom comparator
import java.io.*;
import java.lang.*;
import java.util.*;
class Student {
int r;
String n, a;
// Constructor
public Student(int r, String n, String a)
{
// This keyword refers to current object itself
this.r = r;
this.n = n;
this.a = a;
}
// toString() method to print student details in main()
public String toString()
{
return this.r + " " + this.n + " "
+ this.a;
}
}
// Helper class extending Comparator interface
class Sortbyroll implements Comparator<Student> {
// Used for sorting in ascending order of
// roll number
public int compare(Student x, Student y){
return x.r - y.r;
}
}
class GFG {
public static void main(String[] args){
Student[] x = { new Student(1, "Ram", "MP"),
new Student(2, "Shyam", "UP"),
new Student(3, "Hari", "Delhi") };
// Sorting on basic as per class 1 created
// (user-defined)
Arrays.sort(x, new Sortbyroll());
for (int i = 0; i < x.length; i++)
System.out.println(x[i]);
}
}
Output
1 Ram MP 2 Shyam UP 3 Hari Delhi
Explanation:
- In this example, the students are sorted based on their roll number in ascending order, as specified by the
compare()
method in theSortbyroll
class. - Here, we use a custom comparator to sort the
Student
objects by their roll number, as theStudent
class does not implement theComparable
interface for sorting by roll number. - This allows custom sorting, without modifying the class itself.
Sorting an Array Using Comparable Interface
In the below example, we sort an array of Student objects based on their name alphabetically.
// Java program to sort an array of Student objects
// using Comparable
import java.util.Arrays;
class Student implements Comparable<Student> {
int r;
String n;
String a;
// Constructor
public Student(int r, String n, String a) {
this.r = r;
this.n = n;
this.a = a;
}
// compareTo method to sort by name
public int compareTo(Student o) {
return this.n.compareTo(o.n);
}
// toString() method to print Student details
public String toString() {
return this.r + " " + this.n + " " + this.a;
}
}
public class GFG {
public static void main(String[] args) {
Student[] s = {
new Student(1, "Ram", "UP"),
new Student(2, "Shyam", "MP"),
new Student(3, "Hari", "Bihar")
};
// Sorting students by name in alphabetical order
Arrays.sort(s);
for (Student student : s)
System.out.println(student);
}
}
Output
3 Hari Bihar 1 Ram UP 2 Shyam MP
Explanation:
- In this example, we use the
Comparable
interface here to define a natural ordering for theStudent
objects. - By implementing the
compareTo()
method, we specify how twoStudent
objects should be compared by enabling sorting based on the student’s name. - This allows us to use
Arrays.sort()
method
directly on an array ofStudent
objects to sort them in an order and here we do not need a separate comparator.