Come ordinare un ArrayList in ordine crescente in Java

Dato un ArrayList non ordinato, il compito è ordinare questo ArrayList in ordine crescente in Java.

Esempi:

Ingresso : ArrayList non ordinato: [Geeks, For, ForGeeks, GeeksForGeeks, Un portale di computer]
Produzione : Ordinato ArrayList: [Un portale di computer, For, ForGeeks, Geeks, GeeksForGeeks]

Ingresso : ArrayList non ordinato: [Geeks, For, ForGeeks]
Produzione : ArrayList ordinato: [For, ForGeeks, Geeks]

Approccio: Un ArrayList può essere ordinato utilizzando il metodo sort() della classe Collections in Java. Questo metodo sort() accetta la raccolta da ordinare come parametro e restituisce una raccolta ordinata in ordine crescente per impostazione predefinita.

Sintassi:

Collections.sort(ArrayList); 

Di seguito è riportata l’implementazione dell’approccio di cui sopra:




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

Produzione:

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