Updated December 16, 2023
Table of Content
- Introduction
- Methods of Sorting in Collection
- How Sorting works in Collection?
- Examples of Sorting in Collection
Introduction to Sorting in Collection
The method for sorting in Collections is Collections.sort(), derived from the java.util.Collections class. Programmers can use it to perform sorting based on natural ordering or the order they specify. For that, the Custom comparator has to be used. Even though sorting in the collection is similar to the method java.util.Arrays.sort(), it sorts not only the array elements but the queue, linked list elements, etc.
Syntax
import java.util.collections;
Collections.sort( names_of_elements or list or array )
The above syntax only operates when importing the java.util.Collections class in the Java program. This syntax works for sorting the given collections, such as lists, arrays, set, etc., in ascending or natural order. To sort the given collections in reverse order or descending order there is different syntax within the same class as shown below:
Collections.sort( names_of_elements or list or array, Collections.reverseOrder() );
Methods of Sorting in Collection
The collection.sort() methods for two different types of sorting are:
- sort(List li): Elements of the list “li” will be sorted based on natural ordering, i.e., in ascending order.
- sort(List li, Comparator c): Elements of the list li will be sorted based on comparator c.
How Sorting works in Collection?
Sorting in the collection can occur in various ways. Additionally, it is possible to sort elements of objects, such as string objects, wrapper class objects, and user-defined class objects.
Let us see how sorting can be done in different ways.
1. Sort(List li)
This method helps in sorting the elements based on natural ordering.
Suppose there is a list li, and there are some elements such as 1,4,5,6,9,3,0.
ArrayList<String> li = new ArrayList<String>();
li.add("1");
li.add("4");
li.add("5");
li.add("6");
li.add("9");
li.add("3");
li.add("0");
If we are trying to sort this, the output will be in ascending order, as shown below.
[0, 1, 3, 4, 5, 6, 9]Even though nothing explicit is mentioned, natural ordering is performed based on ascending order.
2. sort(List li, Comparator c)
In some cases, the list can’t be sorted based on natural ordering. At that time, the custom comparator will be used.
Suppose there is a list li and there are some students and their marks as elements.
List<Student1> li = new ArrayList<Student1>();
//add elements to the list li
li.add(new Student1("Anna",40));
li.add(new Student1("Alan",48));
li.add(new Student1("Adu",49));
li.add(new Student1("Iza",50));
Sorting based on their marks requires the use of a custom comparator, as demonstrated below:
Collections.sort(li,new Marks());
Here, the Marks class serves as the comparator, and it requires implementation for comparison.
//class to compare
class Marks implements Comparator<Student1>{
}
Examples of Sorting in Collection
Given below are the examples of Sorting in Collection:
Example #1
Program to sort the elements in a list based on the natural ordering.
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
//class
public class SortCollectionExample {
//main method
public static void main(String[] args) {
// list creation
ArrayList<String> li = new ArrayList<String>();
// Adding elements to a list
li.add("1");
li.add("4");
li.add("5");
li.add("6");
li.add("9");
li.add("3");
li.add("0");
//print the list
System.out.println("Befor sorting, List is: " + li);
// sort the list
Collections.sort(li);
System.out.println("The sorted list is: " + li);
}
}
Output:
Here, we first create a list and add elements to it. After adding the elements, we print the list to identify its order before sorting. Following the print operation, we call the sort() method, and the sorted result is then printed
Example #2
Program to sort the elements in a list based on the custom comparator.
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortComparator {
public static void main(String a[]){
//create a list li for students
List<Student1> li = new ArrayList<Student1>();
//add elements to the list li
li.add(new Student1("Anna",40));
li.add(new Student1("Alan",48));
li.add(new Student1("Adu",49));
li.add(new Student1("Iza",50));
//sort the elements using the comparator Marks
Collections.sort(li,new Marks());
//sorted elements of the list
System.out.println("Sorted list elements are: ");
//print each student details by using for loop
for(Student1 s:li){
System.out.println(s);
}
}
}
//class to compare
class Marks implements Comparator<Student1>{
//compare student details
@Override
public int compare(Student1 s1, Student1 s2) {
//if the mark of student s1,return 1
if(s1.getMark() < s2.getMark()){
return 1;
} else {
return -1;
}
}
}
//student details
class Student1{
//declare variables for name and mark
private String name;
private int mark;
//constructor of class
public Student1(String nm, int mr){
this.name = nm;
this.mark = mr;
}
//get the name
public String getName() {
// return the name
return name;
}
//set the nam
public void setName(String nm) {
//set nm as name
this.name = nm;
}
//get the mark
public int getMark() {
return mark;
}
//set the mark
public void setMark(int mark) {
this.mark = mark;
}
public String toString(){
return "Name is : "+this.name+" and the mark is: "+this.mark;
}
}
Output:
In this program as well, we first create a list and add elements to it. Following the addition of elements, we invoke the sort() method, which includes a custom comparator, Mark. Within that class, the marks of the students are compared with the Student class. The Student class comprises details such as Name and Mark. Subsequent to the comparison, the list is printed based on the descending order of marks.
Example #3
Program to sort the elements in a list in reverse order.
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
//class
public class ReverseSort {
//main method
public static void main(String[] args) {
// list creation
ArrayList<String> li = new ArrayList<String>();
// Adding elements to a list
li.add("1");
li.add("4");
li.add("5");
li.add("6");
li.add("9");
li.add("3");
li.add("0");
//print the list
System.out.println("Befor sorting, List is: " + li);
// sort the list
Collections.sort(li, Collections.reverseOrder());
System.out.println("The sorted list is: " + li);
}
}
Output:
Here, akin to the initial program, we create a list first and add elements to it. After adding the elements, we print the list. Following the print operation, we invoke the sort() method. The difference is that, here, the sorting will be in reverse order. Then, the sorted method will be printed.
Example #3
Code:
import java.util.*;
public class Collectionsorting
{
public static void main(String[] args)
{
ArrayList<String> coll1 = new ArrayList<String>();
coll1.add(" Delhi ");
coll1.add(" Pune ");
coll1.add(" Assam ");
coll1.add(" Bangalore ");
coll1.add(" Harayana ");
coll1.add(" Bihar ");
List<String> names = Arrays.asList("Python", "Java", "Perl", "Ruby", "Fortan");
System.out.println( "Demonstration of collection sort in Java using Collections.sort() fucntion ");
System.out.println("\n");
System. out.println(" The given collection of list of names of places is as follows: ");
System.out.println(names);
Collections.sort(names);
System.out.println("List of names after the use of" +
" Collection.sort() :\n" + names);
System.out.println("\n");
System. out.println(" The given collection of an array of names of places is as follows: ");
System.out.println(coll1);
Collections.sort(coll1);
System.out.println("Array after the use of" +
" Collection.sort() :\n" + coll1);
}
}
Output:
In the given example, we observe the import of the Java.util.collections class, or alternatively, we can import all classes from java.util using java.util*. This implies that all classes belonging to util can be imported. In the main class, we initially declare an array, then proceed to insert each element or name using the add() function. Additionally, we declare a list directly using Arrays.list(). All names are enclosed within double quotes and separated by commas. Then we display all the names as declared using the system. println and then we declared Collections. sort(names) and Collections. sort(coll1) to sort the names specified within lists and arrays in ascending order. The output of the above program can be seen in the above screenshot.
Now let us see another example where we are using Collections. sort() for both ascending and descending order.
Example #4
Code:
import java.util.*;
public class Collectionsorting
{
public static void main(String[] args)
{
ArrayList<String> coll1 = new ArrayList<String>();
coll1.add(" Delhi ");
coll1.add(" Pune ");
coll1.add(" Bihar ");
coll1.add(" Bangalore ");
coll1.add(" Assam ");
coll1.add(" Gujrat ");
System.out.println(" Demonstration of Collections.sort() for sorting the given collections in descending order: ");
System.out.println("\n");
System.out.println(" The given array of names is as follows: ");
System.out.println(coll1);
System.out.println("\n");
Collections.sort(coll1);
System.out.println(" The given array is sorted in ascending order as follows: ");
System.out.println(coll1);
System.out.println("\n");
Collections.sort(coll1, Collections.reverseOrder());
System.out.println("The given array is sorted in descending order is as follows: " +
" Collection.sort() :\n" + coll1);
}
}
Output:
In the above example, we can see it is similar to the previous example, where we have first imported the utility class for using collections class to provide sort() function. Then we have declared an array of names where we have added each element and then we have displayed this array of names using the system. println() then we have declared Collections. sort(coll1) to sort the given array “coll1” in ascending order then to display in descending order we have declared Collections.sort(coll1, Collections.reverseOrder()) to display the names in descending order. In this example, the names displaying ascending order mean displaying names in alphabetical order, and descending means displaying names in reverse order of the ascending order. The output of the above example is as shown in the above screenshot.
Conclusion
Sorting in collections, facilitated by the java.util.Collections class, enhances Java program efficiency. It allows seamless organization of elements in lists, sets, and maps, aiding in improved data manipulation, search, and retrieval through natural ordering or custom comparators.
Recommended Articles
We hope that this EDUCBA information on “Sorting in Collection” was beneficial to you. You can view EDUCBA’s recommended articles for more information