Data Structure & Algorithm in Java

⌘K
  1. Home
  2. Docs
  3. Data Structure & Alg...
  4. Sorting
  5. Sorting in java.util.

Sorting in java.util.

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 the Comparable 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 a Comparator to specify a custom ordering for objects that don’t implement Comparable.
  • 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 the Comparable 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(), the Collections.sort() method can also accept a Comparator 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.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *