logo

Collections.sort() en Java avec exemples

 

java.util.Collections.sort() La méthode est présente dans la classe java.util.Collections. Il est utilisé pour trier les éléments présents dans le spécifié liste de Collection par ordre croissant. Cela fonctionne de la même manière que java.util.Arrays.sort() méthode mais c'est mieux que car elle peut trier les éléments du tableau ainsi que la file d'attente de la liste chaînée et bien d'autres qui y sont présents.

public static void sort(List myList)  

myList : A List type object we want to sort.

This method doesn't return anything

Exemple:

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'}

Tri d'une ArrayList par ordre croissant



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);   }  }  

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

Complexité temporelle : O(N log N) car la complexité temporelle de Collections.sort() est O(nlog(n)).
Espace auxiliaire :O(1)  

Tri d'une ArrayList par ordre décroissant  

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);   }  }  

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

Complexité temporelle : O(N log N) car la complexité temporelle de Collections.sort() est O(nlog(n)).
Espace auxiliaire : O(1)  

Tri d'une ArrayList selon des critères définis par l'utilisateur. Nous pouvons utiliser Interface du comparateur à cet effet. 

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));   }  }  

Sortir
Unsorted 111 bbbb london 131 aaaa nyc 121 cccc jaipur Sorted by rollno 111 bbbb london 121 cccc jaipur 131 aaaa nyc 

Tableaux.sort() vs Collections.sort() Arrays.sort fonctionne pour les tableaux qui peuvent également être de type de données primitif. Collections .sort() fonctionne pour les objets Collections comme Liste de tableaux Liste liée etc. Nous pouvons utiliser Collections.sort() pour trier un tableau après avoir créé une ArrayList d'éléments de tableau donnés.
 

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);   }  }  

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

Arrays.sort() vs Collections.sort() complexité temporelle :

Arrays.sort() utilise un algorithme de tri rapide à double pivot qui donne une complexité temporelle de O(N.log N) qui est généralement plus rapide que les algorithmes de tri rapide traditionnels. D'un autre côté, Collections.sort() crée un tableau d'éléments de liste, les trie à l'aide d'un algorithme de tri de fusion adaptatif et parcourt la liste pour positionner chaque élément à son emplacement correct. Ainsi, pour les types de données primitifs comme int char double etc. Arrays.sort() s'avère bien plus efficace en termes de temps que Collections.sort(). Les problèmes impliquant des types de données primitifs doivent être résolus à l'aide de Arrays.sort() pour une meilleure optimisation.

Voici le code pour démontrer la différence :

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 

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

Nous souhaitons que l'article soit utile aux estimés Geeks. .