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

Published: (March 23, 2026 at 07:16 AM EDT)
1 min read
Source: Dev.to

Source: Dev.to

Java Code

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 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.");
        }
    }
}
0 views
Back to Blog

Related posts

Read more »

two sum- java

Solving Two Sum Using Hashing My Thought Process When I first saw the Two Sum problem, my initial idea was simple: - Target = 9 - Current number = 2 I don’t ne...

bridge99

java private String extractValueObject value { if value == null return 'null'; // 1. Unmask Spring's TypedStringValue immediately if value instanceof TypedStrin...