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";
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:
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:
chars() converts the string to an IntStream of character codes.
sorted() sorts the stream.
mapToObj(c → (char) c) converts the sorted stream back into characters.
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.