Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW