Collections.sort()
The Collections.sort() method in Java is used to sort elements of a List in ascending order. It is part of the java.util.Collections class and works with List implementations like ArrayList and LinkedList. It simplifies sorting by providing a built-in mechanism.
- Sorts elements based on natural ordering or custom Comparator
- Works with List implementations, not arrays
- Modifies the list in-place without creating a new list
Example: Sorting an ArrayList in ascending order
import java.util.*;
public class Collectionsorting
{
public static void main(String[] args)
{
// Create a list of strings
ArrayList<String> al = new ArrayList<String>();
al.add("Geeks For Geeks");
al.add("Friends");
al.add("Dear");
al.add("Is");
al.add("Superb");
/* Collections.sort method is sorting the
elements of ArrayList in ascending order. */
Collections.sort(al);
// Let us print the sorted list
System.out.println("List after the use of" +
" Collection.sort() :\n" + al);
}
}
//List after the use of Collection.sort() :
[Dear, Friends, Geeks For Geeks, Is, Superb]
Custom Sorting
Sorting an ArrayList according to user defined criteria. We can use Comparator Interface for this purpose.
References
https://www.geeksforgeeks.org/java/collections-sort-java-examples/
Top comments (0)