This Java tutorial discusses the different approaches to sort a string alphabetically. When sorting alphabetically, we essentially sort the characters of the string in alphabetical order.
1. Sort a String using Java 8 StreamsThe Stream.sorted() method sorts the stream elements in the natural order. In case of strings, the natural order is the alphabetical order. So we need to perform the following pseudo steps:
The following Java program demonstrates sorting the characters of a string using Stream.sorted()
API.
String string = "adcbgekhs";
String sortedString = Stream.of( string.split("") )
.sorted()
.collect(Collectors.joining());
System.out.println(sortedString); // abcdeghks
2. Sort a String using Arrays.sort()
The Arrays.sort() also does the same thing as Stream.sort() does. So the steps to sort a string remains the same in this solution also. This time, we create a new array of characters, sort the array and then join the array to produce the sorted string.
String string = "adcbgekhs";
//Convert string to char array
char[] chars = string.toCharArray();
//Sort char array
Arrays.sort(chars);
//Convert char array to string
String sortedString = String.valueOf(chars);
System.out.println(sortedChars); // abcdeghks
3. Without using sort() Method
If we do not want to use the inbuilt Java APIs, we can use the Java arrays to iterate over the characters of the String and sort them in a loop.
String string = "adcbgekhs";
String sortedString = sortWithArray(string);
System.out.println(sortedString);
//The custom sorting function using arrays
static String sortWithArray(String str) {
char arr[] = str.toCharArray();
char temp;
int i = 0;
while (i < arr.length) {
int j = i + 1;
while (j < arr.length) {
if (arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j += 1;
}
i += 1;
}
return String.copyValueOf(arr);
}
4. Conclusion
This Java tutorial discusses different ways to sort a string alphabetically with examples. We learned to use the Stream.sort(), Arrays.sort() and custom sort() method using simple arrays and swapping.
Drop me your questions in the comments section.
Happy Learning !!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4