Finding the smallest word in a string using Java 8.
To finding the smallest word in a string, we are using the Stream Api and min() function of Java 8.
- Inside Stream(str.split(“\\s”)) function, we split the string into an array of substrings using regular expression as separator.
- Here min(s1,s2) method we compare the first string length with second string length means first word size is less than the second word.
- Now get() method return the value if present.
- Print the shortest word from string.
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 are :- " + word);
}
}
Output :-
shortest word are :- to
Finding the smallest word in a string using Java 8. Read More »