DEV Community

Kiran Kumar
Kiran Kumar

Posted on

Find the second largest string by length in a sentence using Java 8

import java.util.Arrays;
import java.util.Comparator;
import java.util.Optional;

public class SecondLargestString {
    public static void main(String[] args) {
        String sentence = "The quick brown fox jumps over the lazy dog";

        Optional<String> secondLargest = Arrays.stream(sentence.split("\\s+")) // 1. Split into words
            .distinct() // 2. Remove duplicates (e.g., "The" and "the" would be treated as distinct here unless lowercased first)
            .sorted(Comparator.comparingInt(String::length).reversed() // 3. Sort by length in descending order
                .thenComparing(Comparator.naturalOrder())) // 4. Optional: sort alphabetically for ties in length
            .skip(1) // 5. Skip the longest string
            .findFirst(); // 6. Get the next string (the second longest)

        if (secondLargest.isPresent()) {
            System.out.println("The second largest string is: " + secondLargest.get());
        } else {
            System.out.println("Could not find the second largest string.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)