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:
- The list of words:
["apple", "banana", "cherry", "mango", "kiwi"]
- After sorting by length in descending order:
["banana", "cherry", "apple", "mango", "kiwi"]
.skip(2)
skips the first two words:- Skips
"banana"
and"cherry"
.
- Skips
.findFirst()
picks the next word:- Which is
"apple"
.
- Which is
- The output is printed:
apple