Finding the longest word in a sentence is a short string program that checks how you split text and handle ties and punctuation. Below are a simple loop solution, a Java 8 stream version and a version that returns all words of the maximum length. It pairs with finding the shortest word.

Solution 1: Loop

public class LongestWord {
    public static String longestWord(String sentence) {
        if (sentence == null || sentence.isBlank()) return "";
        String longest = "";
        for (String word : sentence.trim().split("\\s+")) {
            String clean = word.replaceAll("[^A-Za-z0-9]", "");   // ignore punctuation
            if (clean.length() > longest.length()) longest = clean;
        }
        return longest;
    }

    public static void main(String[] args) {
        System.out.println(longestWord("Selenium and Playwright automate browsers."));   // Playwright
    }
}

Using > keeps the first word when two have the same length; use >= to keep the last.

Advertisement

Solution 2: Java 8 Streams

String longest = Arrays.stream(sentence.trim().split("\\s+"))
        .map(w -> w.replaceAll("[^A-Za-z0-9]", ""))
        .max(Comparator.comparingInt(String::length))
        .orElse("");

Solution 3: All Words of Maximum Length

List<String> words = Arrays.stream(sentence.trim().split("\\s+"))
        .map(w -> w.replaceAll("[^A-Za-z0-9]", "")).toList();
int max = words.stream().mapToInt(String::length).max().orElse(0);
List<String> longestWords = words.stream().filter(w -> w.length() == max).distinct().toList();

Complexity and Edge Cases

  • Time O(n) in the length of the sentence; space O(n) for the split words.
  • Handle null or empty input, multiple spaces (\\s+), punctuation attached to words, and ties.
  • Interview follow-up: return the length instead of the word, or find the longest word without using split() by scanning characters.

FAQs

How do you split a sentence into words in Java?

Use sentence.trim().split("\\s+"), which splits on one or more whitespace characters and avoids empty strings from repeated spaces.