The problem with this is that i tried to do it but my method to check the length of the string is not working; what can I do to fix it?
public static void main(String[] args) {
String[] animalNames = {"cat", "rabbit", "horse", "goat", "rooster", "ooooooooooooooo"};
String a= getLongestString(animalNames);
System.out.println(a);
}
public static String getLongestString(String []animalNames) {
// String animalNames[] = {"cat","chicken","horse","ooooooooo" };
int j = 0;
for (j = 0; j <= animalNames.length; j++) {
if (animalNames[j].length() > animalNames[j + 1].length()) {
return (animalNames[j]);
}
}
return null;
}
}
It's real simple using java 8 (just check that your array is not empty first or process the .get()
specially):
List<String> strings = Arrays.asList(animals);
String longest = strings.stream().
max(Comparator.comparingInt(String::length)).get();
int max = longest.length();
OR, if you just need the length:
int max = strings.stream().map(String::length).max(Integer::compareTo).get();
Or, if you prefer a one-liner, it's:
String longest = Arrays.asList(animals)
.strings.stream().max(Comparator.comparingInt(String::length)).get();
=AND=
int max = Arrays.asList(animals)
.stream().map(String::length).max(Integer::compareTo).get();
Well, okay.. it's actually two-liner :-) Enjoy!
UPDATE:
Instead of Arrays.asList(animals).strings.stream()
one could use directly Stream.of(animals)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With