logo

Metoda Java List sort().

The vrsta() metoda List Interface razvrstava dani popis prema redoslijedu navedenom u komparatoru. Popis se mora moći mijenjati, inače će izbaciti iznimku.

Sintaksa

 default void sort(Comparator c) 

Parametri

Parametar 'c' predstavlja komparator koji se koristi za usporedbu elemenata popisa. A za nulte vrijednosti koristi se prirodni poredak.

Povratak

DA

Bacanja:

ClassCastExceptio n- Ako popis sadrži elemente koji nisu međusobno usporedivi korištenjem komparatora

UnsupportedOperationException - Ako list-iterator liste ne podržava operaciju sortiranja

IllegalArgumentException - Ako se utvrdi da komparator krši protokole komparatora.

Primjer 1

 import java.util.Collections; import java.util.LinkedList; import java.util.List; public class JavaListSubListExample3 { public static void main(String[] args) { List list= new LinkedList(); list.add('Renu'); list.add('Heera'); list.add('Vijay'); list.add('Geetanjali'); System.out.println('List : '+list); //will sort the string acc to the alphabets Collections.sort(list); System.out.println('Sorted List : '+list); } } 
Testirajte sada

Izlaz:

 List : [Renu, Heera, Vijay, Geetanjali] Sorted List : [Geetanjali, Heera, Renu, Vijay] 

Primjer 2

 import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Employee { int id; String name; public Employee(int id, String name) { this.id = id; this.name = name; } public String toString() { return this.id + ' ' + this.name ; } } class SortById implements Comparator { // Used for sorting in ascending order of ID public int compare(Employee a, Employee b) { return a.id - b.id; } } // Main class class JavaListSubListExample2 { static int i=1; public static void main (String[] args) { List list = new ArrayList(); Employee employee1 = new Employee(15019, 'Patanjali'); Employee employee2 = new Employee(13198, 'Geetanjali'); Employee employee3 = new Employee(12112, 'Anjali'); list.add(employee1); list.add(employee2); list.add(employee3); System.out.println('Unsorted List : '); for (Employee val : list) { System.out.println(i++ +'. '+val); } Collections.sort(list, new SortById()); System.out.println(); System.out.println(' Sorted List : '); int i=1; for (Employee val : list) { System.out.println(i++ +'. '+val); } } } 
Testirajte sada

Izlaz:

 Unsorted List : 1. 15019 Patanjali 2. 13198 Geetanjali 3. 12112 Anjali Sorted List : 1. 12112 Anjali 2. 13198 Geetanjali 3. 15019 Patanjali