Find the 3rd Longest Word in a List in Java

Problem:
Using Java 8 Streams, how do you find the third longest word in a list without manually sorting and looping through?

✅ Example:

import java.util.Arrays;
import java.util.List;

public class ThirdLongestWord {

    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cherry", "mango", "kiwi");

        words.stream()
                .sorted((w1, w2) -> Integer.compare(w2.length(), w1.length()))  // Sort by length descending
                .skip(2)  // Skip the first two longest words
                .findFirst()  // Get the 3rd longest word
                .ifPresent(System.out::println);
    }
}

✅ Output:

apple

✅Explanation:

  1. The list of words: ["apple", "banana", "cherry", "mango", "kiwi"]
  2. After sorting by length in descending order: ["banana", "cherry", "apple", "mango", "kiwi"]
  3. .skip(2) skips the first two words:
    • Skips "banana" and "cherry".
  4. .findFirst() picks the next word:
    • Which is "apple".
  5. The output is printed: apple

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *