Arrays - Sort in Java With Examples: Sort Method Is A Class Method
Arrays - Sort in Java With Examples: Sort Method Is A Class Method
Syntax:
Arrays.sort(arr);
Output:
Output:
Output:
Output:
Modified arr[] :
Modified arr[] :
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]
We can also sort an array according to user defined criteria.
We use Comparator interface for this purpose. Below is an example.
// Constructor
public Student(int rollno, String name,
String address)
{
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Driver class
class Main
{
public static void main (String[] args)
{
Student [] arr = {new Student(111, "bbbb", "london"),
new Student(131, "aaaa", "nyc"),
new Student(121, "cccc", "jaipur")};
System.out.println("Unsorted");
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
Arrays.sort(arr, new Sortbyroll());
System.out.println("\nSorted by rollno");
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
}
}
Output:
Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur
Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc
Arrays.sort() vs Collections.sort()
Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works
for objects Collections like ArrayList, LinkedList, etc.
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to
contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article
to [email protected]. See your article appearing on the GeeksforGeeks main page
and help other Geeks.