Sort String in Descending Order in Java

1. Introduction

Sorting a string in descending order involves rearranging its characters from 'z' to 'a' and 'Z' to 'A'. This is often required in data sorting, text processing, or when implementing custom ordering rules. In Java, this can be achieved by first converting the string to a character array, sorting the array in ascending order, and then reversing it to get descending order. This tutorial will guide you through sorting the characters of a string in descending order using Java.

Key Points

- Convert the string to a character array.

- Use Arrays.sort() to sort the array in ascending order.

- Reverse the array to achieve descending order.

- Convert the array back to a string.

2. Program Steps

1. Convert the string to a character array.

2. Sort the character array in ascending order.

3. Reverse the array to sort it in descending order.

4. Convert the reversed character array back to a string.

5. Print the sorted string.

3. Code Program

import java.util.Arrays;
import java.util.Collections;

public class SortStringDescending {
    public static void main(String[] args) {
        // Input string
        String input = "java";
        // Convert input string to character array
        Character[] chars = new Character[input.length()];
        for (int i = 0; i < input.length(); i++) {
            chars[i] = input.charAt(i);
        }
        // Sort the character array in ascending order
        Arrays.sort(chars, Collections.reverseOrder());
        // Convert the sorted array back to a string
        StringBuilder sortedString = new StringBuilder(chars.length);
        for (Character c : chars) {
            sortedString.append(c.charValue());
        }
        // Output the sorted string
        System.out.println("Sorted String in Descending Order: " + sortedString.toString());
    }
}

Output:

Sorted String in Descending Order: vjaa

Explanation:

1. String input = "java": Declares and initializes the input string.

2. Character[] chars = new Character[input.length()]: Converts the input string into an array of Character for sorting.

3. Arrays.sort(chars, Collections.reverseOrder()): Sorts the character array in descending order using Arrays.sort() with Collections.reverseOrder().

4. StringBuilder sortedString = new StringBuilder(chars.length): Initializes a StringBuilder to convert the sorted character array back into a string.

5. for (Character c : chars): Appends each character from the sorted array to the StringBuilder.

6. System.out.println("Sorted String in Descending Order: " + sortedString.toString()): Prints the sorted string to the console.


Comments