[Java] How to get a shortest string from an array?
I want to find the shortest string (in terms of length) from an array, How can I do that in Java?
1 Answer
3 years ago by Eleven
Using min
on the stream we can find the shortest string from an array. The following code shows how to do that
import java.util.Arrays;
import java.util.Comparator;
public class JavaArrays {
public static void main(String[] args) {
String[] array = { "blue", "red", "green" };
String result = Arrays.stream(array).min(Comparator.comparingInt(String::length)).get();
System.out.println(result);
}
}
Output:
red
Try code online here: https://onecompiler.com/java/3xmt8gtta
3 years ago by Karthik Divi