Java 中的 Collections.sort() 方法及示例


Collections 類提供了一個增強型靜態方法 `sort()`,用於對列表或陣列中的元素進行排序。對於操作原始集合型別元素的集合,我們也可以使用 TreeSet。`Collections.sort()` 方法位於 `java.util.Collections` 類中,允許使用者按升序對特定列表中的元素進行排序。該方法是 `java.util.Arrays.sort()` 方法類的升級版本,它也能夠對連結串列、佇列等進行排序。簡而言之,Collections 類能夠有效地對列表中的元素進行排序。讓我們來看一個例子:

我們將使用 ``

此過程中可能的 myList > 它是一個 List 型別(任何型別),我們希望從中對物件進行排序。

不幸的是,此方法不會返回任何輸出。

例如

假設我們的列表包含

{"TutorialsPoint", "Friends", "Dear", "Is", "The", "Best", “Hey”}

使用 Collection.sort() 後,我們得到一個排序後的列表:

{“Hey”, "Dear", "Friends", "TutorialsPoint", "Is", "The", "Best"}

有一些方法可以對集合列表中的元素進行排序。使用此方法,我們可以從字串物件、包裝類或使用者定義的類中收集資料。

  • **`public void sort(List list)`** - 此表示法可用於對列表中的元素進行排序。唯一的條件是,現有元素必須具有可比較的型別。這裡我們可以使用字串類和包裝類來實現此過程。要儲存字串和包裝類中存在的物件的 value,它必須具有可比較的性質。

  • **`sort(List list, Comparator c)`** - 此方法根據宣告的 Comparator 類指定的順序對特定列表的元素進行排序。

使用 Collections.sort() 方法的演算法

在這個可能的演算法中,我們將向您展示如何在 Java 環境中應用 Collections.sort() 方法。透過這個演算法,我們將嘗試構建一些語法和一些 Java 程式碼來進一步解釋問題陳述。

  • **步驟 1** - 開始此過程。

  • **步驟 2** - 匯入並宣告可用的 Java 包。

  • **步驟 3** - 宣告一個公共類。

  • **步驟 4** - 構造一個字串引數。

  • **步驟 5** - 建立一個字串列表。

  • **步驟 6** - 透過向其中新增一些資料元素來填充列表。

  • **步驟 7** - 宣告 Collections.sort 方法,以根據流程過濾陣列列表的元素。

  • **步驟 8** - 執行此過程。

  • **步驟 9** - 列印排序列表中的資料元素。

  • **步驟 10** - 獲取結果並終止此過程。

實現 Collections.sort() 方法的語法

Fruit(int id, String name, String taste){
   this.id=id;
   this.name=name;
   this.taste=taste;
}
@Override //Override the method
public int compareTo(Object o) {
   Fruit f = (Fruit) o;
   return this.id - f.id ;
}
}
//Sorting Method 1
Collections.sort(fruitList);
fruitList.forEach(fruit -> {
   System.out.println(fruit.getId() + " " + fruit.getName() + " " +
   fruit.getTaste());
});
//Sorting Method 2
Collections.sort(fruitList, (a, b) -> {
   return a.getName().compareTo(b.getName());
});
//Sorting by using a wrapper class{
ArrayList al=new ArrayList();
al.add(Integer.valueOf(201));
al.add(Integer.valueOf(101));
al.add(230);
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
   System.out.println(itr.next());
}

在上面提到的語法中,我們嘗試以兩種不同的方式向您展示 Collection.sort() 方法的構造過程。透過使用它們,我們正在朝著可能的途徑前進,以透過應用各種 Java 方法來解釋給定的語句。

遵循的方法

  • **方法 1** - Java 程式,用於解釋 Collections.sort() 方法的工作原理

  • **方法 2** - Java 程式,用於說明 Comparator 介面和 Collections.sort() 的工作方法,以便根據使用者定義的條件進行排序

方法 1:演示 Collections.sort() 的工作原理

在這種可能的方法中,我們將向您展示如何以升序方式對 ArrayList 進行排序。對於此過程:

  • **時間複雜度** - 表示為 O(N log N),其中此過程的基本時間複雜度為 O(nlog(n))。

  • **輔助空間** - 輔助空間表示為 O(1)。

示例 1

//Java program to explain the working of a Collections.sort() method
import java.util.*;
public class Collectionsorting0710{
   public static void main(String[] args){
      ArrayList<String> al = new ArrayList<String>();
      al.add("I");
      al.add("AM");
      al.add("GOING");
      al.add("TO");
      al.add("DHAKA");
      Collections.sort(al);
      System.out.println("Here is the list after the use of the" +
      " Collection.sort() method:\n" + al);
   }
}

輸出

Here is the list after the use of the Collection.sort() method:
[AM, DHAKA, GOING, I, TO]

在此特定方法中,我們將操作一個字串類,從中構建另一個 ArrayList。時間複雜度表示為 O(N log N),其中此過程的基本時間複雜度為 O(nlog(n))。輔助空間:輔助空間表示為 O(1)。

示例 2

//Java program to explain the working of the Collections.sort() to a descending order.
import java.util.*;
public class Collectionsorting{
   public static void main(String[] args){
      ArrayList<String> al = new ArrayList<String>();
      al.add("I");
      al.add("AM");
      al.add("GOING");
      al.add("BY");
      al.add("MAITREE EXPRESS");
      Collections.sort(al, Collections.reverseOrder());
      System.out.println("Possible list after the use of the" +
      " Collection.sort() method:\n" + al);
   }
}

輸出

Possible list after the use of the Collection.sort() method:
[MAITREE EXPRESS, I, GOING, BY, AM]

方法 2:使用 Comparator 介面和 Collections.sort() 進行排序操作

現在我們將解釋一些使用者特定的過程,以演示使用 ArrayList 進行排序的過程。

  • 在示例 3 中,我們將使用 Comparator 介面。

  • 在示例 3A 中,我們將向您展示 Arrays.sort() 和 Collections.sort() 之間的區別。

  • 最後,在 3B 中;我們將向您展示 Arrays.sort() 和 Collections.sort() 的時間複雜度。

示例 1

//Java program to illustrate the working method of a Comparator interface and the Collections.sort() to sort according to the user defined criteria.
import java.util.*;
import java.lang.*;
import java.io.*;
class Student{
   int rollno;
   String name, address;
   public Student(int rollno, String name,
   String address){
      this.rollno = rollno;
      this.name = name;
      this.address = address;
   }
   public String toString(){
      return this.rollno + " " + this.name +
      " " + this.address;
   }
}
class Sortbyroll implements Comparator<Student>{
   public int compare(Student a, Student b){
      return a.rollno - b.rollno;
   }
}
public class Main{
   public static void main (String[] args){
      ArrayList<Student> ar = new ArrayList<Student>();
      ar.add(new Student(07, "ARB - 0710", "BAD BRINBACH"));
      ar.add(new Student(16, "RDD - 1610", "ROTTAL INN"));
      ar.add(new Student(2022, "REBA - 2001", "EU CAMPUS"));
      System.out.println("Unsorted Data Elements Present In The List");
      for (int i=0; i<ar.size(); i++)
      System.out.println(ar.get(i));
      Collections.sort(ar, new Sortbyroll());
      System.out.println("\nSorted elements by the Roll Number");
      for (int i=0; i<ar.size(); i++)
      System.out.println(ar.get(i));
   }
}

輸出

Unsorted Data Elements Present In The List
7 ARB - 0710 BAD BRINBACH
16 RDD - 1610 ROTTAL INN
2022 REBA - 2001 EU CAMPUS
Sorted elements by the Roll Number
7 ARB - 0710 BAD BRINBACH
16 RDD - 1610 ROTTAL INN
2022 REBA - 2001 EU CAMPUS

示例 2

import java.util.*;
public class Collectionsort0710{
   public static void main(String[] args){
      String domains[] = {"I", "WILL REACH",
      "BY", "AFTERNOON"};
      List colList =
      new ArrayList(Arrays.asList(domains));
      Collections.sort(colList);
      System.out.println("The list after the use of the" +
      "method of Collection.sort() :\n" +
      colList);
   }
}

輸出

Note: Collectionsort0710.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
The list after the use of themethod of Collection.sort() :
[AFTERNOON, BY, I, WILL REACH]

示例 3

import java.io.*;
import java.util.*;
public class ARBRDD100520220101 {
   public static void main (String[] args) {
      int len = 5000000;
      int[] arr = new int[len];
      for (int i = len; i > 0; i--)
      arr[len - i] = i;
      ArrayList<Integer> list = new ArrayList<>();
      for (int i = len; i > 0; i--)
      list.add(i);
      long startA = System.currentTimeMillis();
      Arrays.sort(arr);
      long stopA = System.currentTimeMillis();
      long startAL = System.currentTimeMillis();
      Collections.sort(list);
      long stopAL = System.currentTimeMillis();
      System.out.println("Time taken by the process of Arrays.sort(): " +
      (stopA - startA));
      System.out.println("Time taken by the process of Collections.sort() is: " + (stopAL - startAL));
   }
}

輸出

Time taken by the process of Arrays.sort() is: 15
Time taken by the process of Collections.sort() is: 31

結論

Collection.sort 過程執行按升序排序的過程。使用此方法,我們可以執行 `reverseOrder()` 操作,該操作返回一個 Comparator 類。另一方面,`reverseOrder(Comparator cmp)` 方法為我們提供了一個返回的 Comparator,它將是該特定 Comparator 類的反向值。在今天的文章中,我們學習了集合類的排序過程。透過使用上述演算法、語法和 Java 程式碼,我們以有效的方式解決了問題陳述。

更新於:2023-12-27

802 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.