Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll look for one of, or all, the longest words of a sentence.

A sentence is a set of words. We’ll represent it with a Java String. Additionally, we’ll assume that every non-whitespace character is part of a word. Lastly, we’ll underline the technical edge cases: a null, empty, or blank String has no longest word.

2. Finding One of the Longest Words

Firstly, let’s find the longest word of the sentence. For instance, in the sentence: “This is a phrase with words”, the longest word is phrase. If various words have the same length, any of them is an acceptable answer. If the sentence has no word, there’s no result. Consequently, our method returns an Optional:

public Optional<String> findLongestWord(String sentence) {
    return Optional.ofNullable(sentence)
      .filter(string -> !string.trim().isEmpty())
      .map(string -> string.split("\\s"))
      .map(Arrays::asList)
      .map(list -> Collections.max(list, Comparator.comparingInt(String::length)));
}

We started by wrapping our sentence into an Optional and filtering out all empty and blank Strings. Next, we applied String‘s split() method to retrieve a word array. We needed to pass it ‘\\s‘ as a parameter to use whitespaces as delimiters. Then, we converted our array into a List thanks to Arrays.asList(). Last but not least, we used Collections.max() to get the word with maximal length. This method has two attributes:

  • the list whose maximum is determined
  • the Comparator to use to determine the maximum

In our case, we compare the words by their length. We called our class LongestWordFinder, so we can now unit test our example sentence:

@Test
void givenAPhraseWithALongestWord_whenFindLongestWord_thenLongestWordOfThePhrase() {
    assertThat(new LongestWordFinder().findLongestWord("This is a phrase with words")).hasValue("phrase");
}

3. Finding All the Longest Words

We’ll now list all the longest words. For example, Baeldung and sentence are the two longest words of the sentence: “Baeldung is another word of size eight in this sentence“.

To start, we’ll get rid of the edge cases with no words and return an empty list in such cases. Besides, we’ll once again split the sentence into a word array. However, this time our goal will be to calculate the maximal length first and use it to find all words having this length:

public List<String> findLongestWords(String sentence) {
    if (sentence == null || sentence.trim().isEmpty()) {
        return Collections.emptyList();
    }
    String[] words = sentence.split("\\s");
    int maxWordLength = Arrays.stream(words)
      .mapToInt(String::length)
      .max()
      .orElseThrow();
    return Arrays.stream(words)
      .filter(word -> word.length() == maxWordLength)
      .collect(Collectors.toList());
}

As we can see, to compute the maximal length, we created a Stream out of our word array first. Then, we applied the mapToInt() intermediate operation with String::length as a parameter. This way, we converted our Stream into a Stream of words lengths. Lastly, we got the maximal value of the Stream.

To conclude, all we needed to do was filter the words having this maximal length. We used another Stream to do this and collect the matching words into the result list. Let’s now check that findLongestWords() returns the expected result for our example sentence:

@Test
void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWords_thenAllLongestsWords() {
    assertThat(new LongestWordFinder().findLongestWords("Baeldung is another word of size eight in this sentence")).containsExactly("Baeldung", "sentence");
}

4. Conclusion

In this article, we split a sentence into a list of words and used the Collections API to find one of the longest words. We’ve also seen how to use Java Streams to find them all.

As always the code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.