Kā kārtot ArrayList augošā secībā Java

Ņemot vērā nešķiroto ArrayList, uzdevums ir kārtot šo ArrayList augošā secībā Java.

Piemēri:

Ievade : Nešķirots ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, datora portāls]
Izvade : Sakārtots ArrayList: [Datora portāls, For, ForGeeks, Geeks, GeeksForGeeks]

Ievade : Nešķirots ArrayList: [Geeks, For, ForGeeks]
Izvade : Sakārtots ArrayList: [For, ForGeeks, Geeks]

Pieeja: ArrayList var kārtot, izmantojot Java kolekcijas klases sort() metodi. Šī sort() metode izmanto kārtojamo kolekciju kā parametru un atgriež kolekciju, kas pēc noklusējuma ir sakārtota augošā secībā.

Sintakse:

Collections.sort(ArrayList); 

Tālāk ir aprakstīta iepriekš minētās pieejas īstenošana.




// Java program to demonstrate> // How to sort ArrayList in ascending order> > import> java.util.*;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // Get the ArrayList> > ArrayList> > list => new> ArrayList();> > > // Populate the ArrayList> > list.add(> 'Geeks'> );> > list.add(> 'For'> );> > list.add(> 'ForGeeks'> );> > list.add(> 'GeeksForGeeks'> );> > list.add(> 'A computer portal'> );> > > // Print the unsorted ArrayList> > System.out.println(> 'Unsorted ArrayList: '> > + list);> > > // Sorting ArrayList in ascending Order> > // using Collection.sort() method> > Collections.sort(list);> > > // Print the sorted ArrayList> > System.out.println(> 'Sorted ArrayList '> > +> 'in Ascending order : '> > + list);> > }> }>

Izvade:

 Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Sorted ArrayList in Ascending order : [A computer portal, For, ForGeeks, Geeks, GeeksForGeeks]