Here is the detailed explanation of Sorting in java.util.
In Java, the java.util
package provides several sorting methods for arrays and collections.
Here’s an overview of some commonly used sorting methods available in Java:
Arrays.sort() method:
- The
Arrays.sort()
method is used to sort arrays of primitive data types (int
,double
,char
, etc.) or objects that implement theComparable
interface. - For arrays of primitive types, the elements are sorted into ascending order.
- For arrays of objects, the elements are sorted based on the natural ordering defined by the
compareTo()
method of the objects. - Example:
int[] arr = {5, 3, 7, 1, 9};
Arrays.sort(arr); // Sorts the array in ascending order
Arrays.sort() method with Comparator:
- The
Arrays.sort()
method can also be used with aComparator
to specify a custom ordering for objects that don’t implementComparable
. - Example:
String[] names = {"Savvy", "Aarik", "Ronast"};
Arrays.sort(names, Comparator.reverseOrder()); // Sorts the array in descending order
Collections.sort() method:
- The
Collections.sort()
method is used to sort collections (e.g.,ArrayList
,LinkedList
, etc.) that contain objects implementing theComparable
interface. - It sorts the elements of the collection into ascending order based on the natural ordering defined by the
compareTo()
method. - Example:
ArrayList<Integer> numbers = new ArrayList<>(List.of(5, 3, 7, 1, 9));
Collections.sort(numbers); // Sorts the list in ascending order
Collections.sort() method with Comparator:
- Similar to
Arrays.sort()
, theCollections.sort()
method can also accept aComparator
to specify a custom ordering. - Example:
ArrayList<String> names = new ArrayList<>(List.of("Savvy", "Aarik", "Ronast"));
Collections.sort(names, Comparator.reverseOrder()); // Sorts the list in descending order
These sorting methods provided by java.util
package offer convenient ways to sort arrays and collections in Java based on natural ordering or custom criteria.