Introduction
Finding the shortest word is useful for text analysis and data validation.
Method 1: Using Loop
public class FindShortestWord {
public static String findShortestWord(String sentence) {
if (sentence == null || sentence.isEmpty()) {
return "";
}
String[] words = sentence.split(" ");
String shortest = words[0];
for (String word : words) {
if (word.length() < shortest.length()) {
shortest = word;
}
}
return shortest;
}
public static void main(String[] args) {
System.out.println(findShortestWord("The quick brown fox")); // The
}
}
Output:
The
Method 2: Using Streams
import java.util.Arrays;
public class FindShortestWordStream {
public static String findShortestWord(String sentence) {
return Arrays.stream(sentence.split(" "))
.reduce((w1, w2) -> w1.length() < w2.length() ? w1 : w2)
.orElse("");
}
}
Method 3: Using Collections.min()
import java.util.Arrays;
import java.util.Collections;
public class FindShortestWordCollection {
public static String findShortestWord(String sentence) {
return Collections.min(
Arrays.asList(sentence.split(" ")),
(w1, w2) -> Integer.compare(w1.length(), w2.length())
);
}
}
Frequently Asked Questions
Q1. What about single-letter words?
Answer: Returned if present and shortest.
Q2. Empty string handling?
Answer: Check and filter before processing.
Q3. Performance?
Answer: All O(n), same complexity.
Q4. Multiple shortest?
Answer: Returns first one.
Q5. Case matters?
Answer: No, length comparison is case-independent.
Q6. Ignore punctuation?
Answer: Remove or handle in comparison.
Q7. Unicode support?
Answer: Yes, all methods support it.
Q8. Collect all shortest?
Answer: Filter by min length.
Q9. Large sentences?
Answer: All scale linearly O(n).
Q10. Both longest and shortest?
Answer: Run both methods or combine logic.