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

관련 글

더 보기 »

SJF4J: Java용 구조화된 JSON 파사드

소개 Java에서 JSON을 다루는 것은 일반적으로 두 가지 접근 방식 중 하나를 선택하는 것을 의미합니다: - 데이터 바인딩 POJO – 강한 타입 지정이지만 경직됨 - 트리 모델 JsonNode / Ma...

다음 순열

문제 설명: 주어진 숫자 배열의 next permutation을 계산하는 것이 과제이다. permutation은 동일한 원소들의 재배열이며, 다음…