Learn how to find the smallest word in a string using Java 8 Stream API and the min() method with a simple example.
Code Explanation (Step-by-Step)
- Create a string containing multiple words.
- Use str.split(“\\s”) to divide the string into words.
- Convert the array into a stream using Arrays.stream() .
- Use the min(s1,s2) method to find the shortest word.
- Compare words based on their lengths using Integer.compare(s1.length(), s2.length()) .
- Retrieve the result using get().
- Print the shortest word.
import java.util.Arrays;
public class ShortestWord {
public static void main(String[] args) {
String str = "welcome to java";
String word = Arrays.stream(str.split("\\s"))
.min((s1, s2) -> Integer.compare(s1.length(), s2.length()))
.get();
System.out.println("Shortest word is :- " + word);
}
}
Output :
Shortest word is :- to
How Stream API Finds the Shortest Word
import java.util.Arrays;
public class ShortestWord {
public static void main(String[] args) {
String str = "welcome to java stream api";
String shortest = Arrays.stream(str.split("\\s"))
.reduce((w1, w2) -> w1.length() < w2.length() ? w1 : w2)
.orElse("");
System.out.println("Shortest word is : " + shortest);
}
}
Output :
Shortest word is :- to
FAQ
How do you find the smallest word in a string in Java 8?
Use the Stream API with the min() method and compare words based on their length.
What does split(“\\s”) do in Java?
It splits a string into words using whitespace as the delimiter.
Why is min() used in Java Streams?
The min() method returns the smallest element according to the provided comparator.
What does Comparator.comparingInt(String::length) do?
It compares strings based on their length and helps identify the shortest string.
Can this approach find the longest word as well?
Yes, by replacing min() with max().