Metoda sort () Java

W Javie struktura kolekcji udostępnia statyczną metodę sort (), której można użyć do sortowania elementów w kolekcji.

sort()Metoda ramach kolekcji wykorzystuje algorytm scalania sortowania, aby posortować elementy kolekcji.

Algorytm sortowania przez scalanie jest oparty na zasadzie dzielenia i zwycięstwa. Aby dowiedzieć się więcej o sortowaniu przez scalanie, odwiedź stronę Algorytm sortowania przez scalanie.

Weźmy przykład sort()metody.

Przykład: sortowanie w porządku rosnącym

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

Wynik

 Unsorted ArrayList: (4, 2, 3) Sorted ArrayList: (2, 3, 4) 

Jak widać, domyślnie sortowanie odbywa się w kolejności naturalnej (rosnącej). Możemy jednak dostosować kolejność sortowania sort()metody.

Indywidualna kolejność sortowania

W Javie sort()metodę można dostosować do sortowania w odwrotnej kolejności za pomocą Comparatorinterfejsu.

Przykład: sortowanie w porządku malejącym

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

Wynik

 Unsorted ArrayList: (4, 2, 3) Sortowanie naturalne: (2, 3, 4) Sortowanie niestandardowe: (4, 3, 2) 

W powyższym przykładzie użyliśmy sort()metody z CustomComparator jako argumentem.

Tutaj CustomComparator jest klasą implementującą Comparatorinterfejs. Dowiedz się więcej o interfejsie Java Comparator.

Następnie nadpisujemy compare()metodę. Metoda będzie teraz sortować elementy w odwrotnej kolejności.

Interesujące artykuły...