Java 8을 사용하여 문장에서 길이 기준 두 번째로 큰 문자열 찾기
발행: (2026년 3월 23일 PM 08:16 GMT+9)
1 분 소요
원문: Dev.to
Source: Dev.to
Java 코드
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.");
}
}
}