Java program to sort string array in descending order using collections

Program

import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;
public class SortStringArrayInDecendingOrderUsingCollections{
    public static void main(String[] args) {
        int i = 0;
        System.out.println("Enter the required size of the array: ");
        Scanner reader = new Scanner(System.in);
        int size = reader.nextInt();
        String inputArray[] = new String[size];
        System.out.println("Enter the elements of the array: ");
        for (i = 0; i < size; i++) {
          inputArray[i] = reader.next();
        }
        Arrays.sort(inputArray, Collections.reverseOrder()); 
        System.out.println("String Array elements sorted in decending order: ");
        System.out.println(Arrays.toString(inputArray));
      }
}

This program demonstrates sorting a string array in descending order using Java's Collections.reverseOrder() with the Arrays.sort() method.

  1. Input Handling:

    • The user is prompted to enter the size of the string array.
    • The user then provides the elements of the array.
  2. Sorting Logic:

    • Arrays.sort() is used to sort the array.
    • The Collections.reverseOrder() method is passed as a comparator to sort the elements in descending (reverse) order.
  3. Output:

    • The program prints the array sorted in descending order.
  4. Key Methods Used:

    • Arrays.sort(inputArray, Collections.reverseOrder()): Sorts the array in reverse order.

Key Features:

  1. Built-in Methods:
    • Uses Java's built-in sorting methods, simplifying the implementation.
  2. Descending Order:
    • Utilizes Collections.reverseOrder() for reverse sorting.

Advantages:

  • Simple and efficient for small to medium-sized arrays.
  • Easy to implement due to built-in Java utilities.

Limitations:

  • Relies on built-in methods, so the internal sorting mechanism isn't explicitly visible.
  • The array must contain non-null strings as Collections.reverseOrder() doesn't handle null values.

Output

javac .\SortStringArrayInDecendingOrderUsingCollections.java
java SortStringArrayInDecendingOrderUsingCollections        
Enter the required size of the array: 
4
Enter the elements of the array: 
java
python
ada
php
String Array elements sorted in decending order: 
[python, php, java, ada]