Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the longest string in an array of Strings

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;
    }

}
like image 684
Dee Avatar asked Nov 03 '14 23:11

Dee


1 Answers

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)

like image 88
Nestor Milyaev Avatar answered Nov 14 '22 22:11

Nestor Milyaev