Sort Words in a String in Java
Problem
Sorting a sentence's words means rearranging the words themselves into alphabetical order, while each word's own letters stay exactly as they were.
Given a sentence, arrange its words in alphabetical order.
Java Program
import java.util.Arrays;
public class SortWords {
public static void main(String[] args) {
String str = "banana apple cherry";
String[] words = str.split(" "); // break the sentence into individual words
Arrays.sort(words); // sorts the array in place, using each word's natural (dictionary) order
System.out.println(String.join(" ", words)); // stitches the sorted words back into a sentence
}
}Output
Core Logic
Splitting the sentence into an array of words, sorting that array, and joining it back together reorders the words alphabetically.
- 1
str.split(" ")breaks the sentence into an array of individual words. - 2
Arrays.sort(words)sorts the array ofStrings in place, using each word's natural (dictionary) ordering. - 3
String.join(" ", words)stitches the now-sorted words back into a single sentence, with single spaces between them.
"banana apple cherry", the array ["banana", "apple", "cherry"] sorts to ["apple", "banana", "cherry"], producing "apple banana cherry".Key Point: Arrays.sort() on an array of Strings compares them lexicographically — the same character-by-character comparison String.compareTo() uses, not by word length.
Why: split() allocates an array of words, and sorting that array costs O(n log n) comparisons, where each comparison itself scans the words being compared.
Key Concepts
Approach 2: Java 8
import java.util.Arrays;
import java.util.stream.Collectors;
public class SortWordsStream {
public static void main(String[] args) {
String str = "banana apple cherry";
// sorted() sorts the words; Collectors.joining() rejoins them into a sentence
String result = Arrays.stream(str.split(" "))
.sorted()
.collect(Collectors.joining(" "));
System.out.println(result);
}
}
Output
Core Logic
The same sort can be expressed as a stream pipeline — sort the stream of words directly, then join them back into a sentence.
- 1
Arrays.stream(str.split(" "))turns the split words into aStream<String>. - 2
.sorted()sorts the stream using each word's natural ordering, the stream equivalent ofArrays.sort(). - 3
.collect(Collectors.joining(" "))joins the sorted words back together with single spaces between them.
["banana", "apple", "cherry"] and joining the result produces the same sentence as the array version: "apple banana cherry".Key Point: This does the same O(n log n) sort as the array version, just expressed as a stream pipeline instead of a mutation-in-place call.
Why: sorted() still performs the same comparison sort over the words, and Collectors.joining() builds a result string holding the whole sentence.