Cum să sortați o ArrayList în ordine crescătoare în Java
Având în vedere un ArrayList nesortat, sarcina este de a sorta această ArrayList în ordine crescătoare în Java.
Exemple:
Intrare : Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, Un portal de computer]
Ieșire : Sorted ArrayList: [Un portal de computer, Pentru, ForGeeks, Geeks, GeeksForGeeks]Intrare : ArrayList nesortată: [Geeks, For, ForGeeks]
Ieșire : ArrayList sortată: [Pentru, ForGeeks, Geeks]
Abordare: Un ArrayList poate fi Sortat folosind metoda sort() a clasei Collections din Java. Această metodă sort() preia colecția să fie sortată ca parametru și returnează o colecție sortată în ordine crescătoare în mod implicit.
Sintaxă:
Collections.sort(ArrayList);
Mai jos este implementarea abordării de mai sus:
// 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);> > }> }> |
Ieșire:
Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Sorted ArrayList in Ascending order : [A computer portal, For, ForGeeks, Geeks, GeeksForGeeks]