How can I sort a String in Java?

Is there a native way in Java to sort a string by its contents? For example, if I have:

String s = "edcba";

How can I sort it to get:

"abcde";

Hi Priyanka,

One simple approach to sort a string is to convert the string into a character array, use Arrays.sort() to sort the characters, and then convert it back into a string. Here’s how you can do it:

import java.util.Arrays;

public class SortString {
    public static void main(String[] args) {
        String s = "edcba";
        char[] charArray = s.toCharArray(); // Convert string to character array
        Arrays.sort(charArray); // Sort the character array
        String sortedString = new String(charArray); // Convert back to string
        System.out.println(sortedString); // Output: abcde
    }
}

Explanation:

  1. toCharArray() converts the string to a character array.
  2. Arrays.sort() sorts the array alphabetically.
  3. Then, you can easily convert the sorted character array back into a string.
  4. This is one of the most straightforward ways to java sort string alphabetically.

If you’re working with Java 8 or higher, you can take advantage of the Stream API to sort the string. This method is more functional and compact. Here’s an example:

import java.util.stream.Collectors;

public class SortString {
    public static void main(String[] args) {
        String s = "edcba";
        String sortedString = s.chars()                      // Create an IntStream from the string
                               .sorted()                    // Sort the stream of characters
                               .mapToObj(c -> (char) c)    // Convert int values to characters
                               .map(String::valueOf)        // Convert characters to strings
                               .collect(Collectors.joining()); // Join them back into a string
        System.out.println(sortedString); // Output: abcde
    }
}

Explanation:

  1. chars() converts the string to an IntStream of character codes.

  2. sorted() sorts the stream.

  3. mapToObj(c → (char) c) converts the sorted stream back into characters.

  4. Finally, Collectors.joining() combines the characters into a sorted string. This solution is more elegant and utilizes Java’s modern features to java sort string using streams.