Here is the detailed explanation of Sorting in java.util.
Thank you for reading this post, don't forget to subscribe!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 theComparableinterface. - 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 orderArrays.sort() method with Comparator:
- The
Arrays.sort()method can also be used with aComparatorto 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 orderCollections.sort() method:
- The
Collections.sort()method is used to sort collections (e.g.,ArrayList,LinkedList, etc.) that contain objects implementing theComparableinterface. - 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 orderCollections.sort() method with Comparator:
- Similar to
Arrays.sort(), theCollections.sort()method can also accept aComparatorto 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 orderThese sorting methods provided by java.util package offer convenient ways to sort arrays and collections in Java based on natural ordering or custom criteria.