Phương thức sắp xếp () trong Java

Trong Java, khung công tác tập hợp cung cấp một phương thức tĩnh sort () có thể được sử dụng để sắp xếp các phần tử trong một tập hợp.

Các sort()phương pháp khuôn khổ bộ sưu tập sử dụng các thuật toán sắp xếp hợp nhất để sắp xếp các yếu tố của một bộ sưu tập.

Thuật toán sắp xếp hợp nhất dựa trên quy tắc chia và chinh phục. Để tìm hiểu thêm về sắp xếp hợp nhất, hãy truy cập Thuật toán sắp xếp hợp nhất.

Hãy lấy một ví dụ về sort()phương pháp này.

Ví dụ: Sắp xếp theo thứ tự tăng dần

 import java.util.ArrayList; import java.util.Collections; class Main ( public static void main(String() args) ( // Creating an array list ArrayList numbers = new ArrayList(); // Add elements numbers.add(4); numbers.add(2); numbers.add(3); System.out.println("Unsorted ArrayList: " + numbers); // Using the sort() method Collections.sort(numbers); System.out.println("Sorted ArrayList: " + numbers); ) ) 

Đầu ra

 Danh sách mảng không được sắp xếp: (4, 2, 3) Danh sách mảng được sắp xếp: (2, 3, 4) 

Như bạn có thể thấy, theo mặc định, việc sắp xếp diễn ra theo thứ tự tự nhiên (thứ tự tăng dần). Tuy nhiên, chúng ta có thể tùy chỉnh thứ tự sắp xếp của sort()phương thức.

Thứ tự sắp xếp tùy chỉnh

Trong Java, sort()phương thức có thể được tùy chỉnh để thực hiện sắp xếp theo thứ tự ngược lại bằng cách sử dụng Comparatorgiao diện.

Ví dụ: Sắp xếp theo thứ tự giảm dần

 import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class Main ( public static void main(String() args) ( // Creating an array list ArrayList numbers = new ArrayList(); // Add elements numbers.add(4); numbers.add(2); numbers.add(3); System.out.println("Unsorted ArrayList: " + numbers); // Using the sort() method Collections.sort(numbers); System.out.println("Natural Sorting: " + numbers); // Using the customized sort() method Collections.sort(numbers, new CustomComparator()); System.out.println("Customized Sorting: " + numbers); ) ) class CustomComparator implements Comparator ( @Override public int compare(Integer animal1, Integer animal2) ( int value = animal1.compareTo(animal2); // elements are sorted in reverse order if (value> 0) ( return -1; ) else if (value < 0) ( return 1; ) else ( return 0; ) ) ) 

Đầu ra

 Danh sách mảng không được phân loại: (4, 2, 3) Sắp xếp tự nhiên: (2, 3, 4) Sắp xếp tùy chỉnh: (4, 3, 2) 

Trong ví dụ trên, chúng tôi đã sử dụng sort()phương thức với CustomComparator làm đối số.

Ở đây, CustomComparator là một lớp thực thi Comparatorgiao diện. Tìm hiểu thêm về Giao diện so sánh Java.

Sau đó, chúng tôi ghi đè compare()phương thức. Phương thức bây giờ sẽ sắp xếp các phần tử theo thứ tự ngược lại.

thú vị bài viết...