Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Vector subList() Method in Java
Next article icon

Collections.sort() in Java with Examples

Last Updated : 04 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
 

java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order. It works similar to java.util.Arrays.sort() method but it is better than as it can sort the elements of Array as well as linked list, queue and many more present in it.

public static void sort(List myList)

myList : A List type object we want to sort.

This method doesn't return anything

Example:

Let us suppose that our list contains
{"Geeks For Geeks", "Friends", "Dear", "Is", "Superb"}

After using Collection.sort(), we obtain a sorted list as
{"Dear", "Friends", "Geeks For Geeks", "Is", "Superb"}

Sorting an ArrayList in ascending order

JAVA
// Java program to demonstrate working of Collections.sort()  import java.util.*;   public class Collectionsorting  {      public static void main(String[] args)      {          // Create a list of strings          ArrayList<String> al = new ArrayList<String>();          al.add("Geeks For Geeks");          al.add("Friends");          al.add("Dear");          al.add("Is");          al.add("Superb");           /* Collections.sort method is sorting the          elements of ArrayList in ascending order. */         Collections.sort(al);           // Let us print the sorted list          System.out.println("List after the use of" +                          " Collection.sort() :\n" + al);      }  }  

Output
List after the use of Collection.sort() : [Dear, Friends, Geeks For Geeks, Is, Superb] 

Time Complexity: O(N log N) as time complexity of Collections.sort() is O(nlog(n)).
Auxiliary Space: O(1)  

Sorting an ArrayList in descending order 

JAVA
// Java program to demonstrate working of Collections.sort()  // to descending order.  import java.util.*;   public class Collectionsorting  {      public static void main(String[] args)      {          // Create a list of strings          ArrayList<String> al = new ArrayList<String>();          al.add("Geeks For Geeks");          al.add("Friends");          al.add("Dear");          al.add("Is");          al.add("Superb");           /* Collections.sort method is sorting the          elements of ArrayList in ascending order. */         Collections.sort(al, Collections.reverseOrder());           // Let us print the sorted list          System.out.println("List after the use of" +                          " Collection.sort() :\n" + al);      }  }  

Output
List after the use of Collection.sort() : [Superb, Is, Geeks For Geeks, Friends, Dear] 

Time Complexity: O(N log N) as time complexity of Collections.sort() is O(nlog(n)).
Auxiliary Space: O(1)  

Sorting an ArrayList according to user defined criteria. We can use Comparator Interface for this purpose. 

Java
// Java program to demonstrate working of Comparator  // interface and Collections.sort() to sort according  // to user defined criteria.  import java.util.*;  import java.lang.*;  import java.io.*;   // A class to represent a student.  class Student  {      int rollno;      String name, address;       // Constructor      public Student(int rollno, String name,                              String address)      {          this.rollno = rollno;          this.name = name;          this.address = address;      }       // Used to print student details in main()      public String toString()      {          return this.rollno + " " + this.name +                          " " + this.address;      }  }   class Sortbyroll implements Comparator<Student>  {      // Used for sorting in ascending order of      // roll number      public int compare(Student a, Student b)      {          return a.rollno - b.rollno;      }  }   // Driver class  class Main  {      public static void main (String[] args)      {          ArrayList<Student> ar = new ArrayList<Student>();          ar.add(new Student(111, "bbbb", "london"));          ar.add(new Student(131, "aaaa", "nyc"));          ar.add(new Student(121, "cccc", "jaipur"));           System.out.println("Unsorted");          for (int i=0; i<ar.size(); i++)              System.out.println(ar.get(i));           Collections.sort(ar, new Sortbyroll());           System.out.println("\nSorted by rollno");          for (int i=0; i<ar.size(); i++)              System.out.println(ar.get(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. We can use Collections.sort() to sort an array after creating an ArrayList of given array items.
 

JAVA
// Using Collections.sort() to sort an array  import java.util.*;  public class Collectionsort  {      public static void main(String[] args)      {          // create an array of string objs          String domains[] = {"Practice", "Geeks",                              "Code", "Quiz"};           // Here we are making a list named as Collist          List colList =              new ArrayList(Arrays.asList(domains));           // Collection.sort() method is used here          // to sort the list elements.          Collections.sort(colList);           // Let us print the sorted list          System.out.println("List after the use of" +                          " Collection.sort() :\n" +                          colList);      }  }  

Output
List after the use of Collection.sort() : [Code, Geeks, Practice, Quiz] 

Arrays.sort() vs Collections.sort() time complexity :

Arrays.sort() uses a Dual-Pivot Quicksort algorithm which gives a time complexity of O(N.log N) which is typically faster than traditional Quicksort algorithms. On the other hand, Collections.sort() creates an array of list elements, sorts them using an adaptive Mergesort algorithm, and iterates over the list to position each element at its correct location. Thus for primitive datatypes like int, char, double, etc. Arrays.sort() proves to be way more time efficient than Collections.sort(). Problems involving primitive datatypes should be tried to solve using Arrays.sort() for better optimisation.

Below is the code to demonstrate the difference:

Java
/*package whatever //do not write package name here */  import java.io.*; import java.util.*;  class GFG {     public static void main (String[] args) {         int len = 5000000;                  // creating a large test array         int[] arr = new int[len];         for (int i = len; i > 0; i--)             arr[len - i] = i;                  // creating a large test arraylist         ArrayList<Integer> list = new ArrayList<>();         for (int i = len; i > 0; i--)             list.add(i);                    // calculating time used by arrays.sort()         long startA = System.currentTimeMillis();         Arrays.sort(arr);         long stopA = System.currentTimeMillis();                    // calculating time used by collections.sort()           long startAL = System.currentTimeMillis();           Collections.sort(list);           long stopAL = System.currentTimeMillis();                    System.out.println("Time taken by Arrays.sort(): " + (stopA - startA));         System.out.println("Time taken by Collections.sort(): " + (stopAL - startAL));     } }  // This code is contributed by godcoder28 

Output
Time taken by Arrays.sort(): 29 Time taken by Collections.sort(): 42 

The article is wished to be useful to the esteemed Geeks. .



Next Article
Vector subList() Method in Java

M

Mohit Gupta
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • Vector lastElement() Method in Java
    The java.util.vector.lastElement() method in Java is used to retrieve or fetch the last element of the Vector. It returns the element present at the last index of the vector. Syntax: Vector.lastElement() Parameters: The method does not take any parameter. Return Value: The method returns the last el
    2 min read
  • Vector lastIndexOf() Method in Java
    The Java.util.Vector.lastIndexOf(Object element) method is used to check and find the occurrence of a particular element in the vector. If the element is present in the vector then the lastIndexOf() method returns the index of last occurrence of the element otherwise it returns -1. This method is us
    2 min read
  • Vector listIterator() method in Java with Examples
    java.util.Vector.listIterator() This method returns a list iterator over the elements of a Vector object in proper sequence. It is bidirectional, so both forward and backward traversal is possible, using next() and previous() respectively. The iterator thus returned is fail-fast. This means that str
    3 min read
  • Vector removeAll() Method in Java
    The java.util.vector.removeAll(Collection col) method is used to remove all the elements from the vector, present in the collection specified. Syntax: Vector.removeAll(Collection col) Parameters: This method accepts a mandatory parameter col which is the collection whose elements are to be removed f
    2 min read
  • Vector removeAllElements() method in Java with Example
    The Java.util.Vector.removeAllElements() method is used to removes all components from this Vector and sets its size to zero. Syntax: Vector.removeAllElements() Parameters: The method does not take any parameter Return Value: The function does not returns any value. Below programs illustrate the Jav
    2 min read
  • Vector removeElement() method in Java with Example
    The java.util.Vector.removeElement() method is used to remove first occurrence of particular object. If object is not found then it returns false else it returns true. If a particular object is present inside vector and removeElement() method call on that vector element then this method reduces vect
    3 min read
  • Vector removeElementAt() Method in Java
    The java.util.vector.removeElementAt(int index) method is used to remove an element from a Vector from a specific position or index. In this process the size of the vector is automatically reduced by one and all other elements after the removed element are shifted downwards by one position. Syntax:
    2 min read
  • Vector removeIf() method in Java
    The removeIf() method of Vector removes all of those elements from Vector which satisfies the condition passed as a parameter to this method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or
    3 min read
  • Vector removeRange() method in Java with Example
    The removeRange() method of Vector in Java is used to remove all elements within the specified range from an Vector object. It shifts any succeeding elements to the left. This call shortens the Vector by (toIndex-fromIndex) elements where toIndex is the ending index and fromIndex is the starting ind
    3 min read
  • Vector retainAll() method in Java with Examples
    The retainAll method of class vector in java is an inbuilt function in Java which is used to retains only the elements in this Vector that are contained in the specified Collection. In other words, removes from this Vector all of its elements that are not contained in the specified Collection. Synta
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences