โ๏ธCloud & DevOps
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 secondLargest = Arrays.stream(sentence.split("\\s+")) // 1. Split int
โกQuick SummaryAI generating...
K
Kiran Kumar
๐ก
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.");
}
}
}
Tags:#cloud#dev.to
Found this useful? Share it!
Read the Full Story
Continue reading on Dev.to
Related Stories
โ๏ธ
โ๏ธCloud & DevOps
I wanted shadcn/ui for Blazor. It didnโt exist. So I built it.
about 19 hours ago
โ๏ธ
โ๏ธCloud & DevOps
Shipping Fast with AI? Youโre Probably Shipping Vulnerabilities Too.
about 19 hours ago

โ๏ธCloud & DevOps
Oops, I Vibecoded Again. Please Help Me! โ A CSS Refiner
about 19 hours ago

โ๏ธCloud & DevOps
๐ณ Dรฉtection de Fraude Bancaire & IA : Ma contribution au Notion MCP Challenge
about 19 hours ago