int index = 0;
int elementLength = array[0].length();
for(int i=1; i< array.length(); i++) {
if(array[i].length() > elementLength) {
index = i; elementLength = array[i].length();
}
}
return array[index];
// Find longest String in a List
public void changeList(List<String> list) {
String longestString = list.stream().max(Comparator.comparingInt(String::length)).get();
}
public class JavaLongestStringInStringArray {
public static String getLongestString(String[] array) {
int maxLength = 0;
String longestString = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
longestString = s;
}
}
return longestString;
}
public static void main(String[] args) {
String[] toppings = {"Cheese", "Pepperoni", "Black Olives"};
String longestString = getLongestString(toppings);
System.out.format("longest string: '%s'
", longestString);
}
}