PHpullh
학습 라이브러리/Java/Optional 체이닝

JAVA · 함수형/Stream

Optional 체이닝

Optional을 함수형으로 체이닝하여 null 안전한 코드를 작성합니다.

함수형/Stream중급Optional체이닝flatMapnull안전

핵심 설명

Optional을 함수형으로 체이닝하여 null 안전한 코드를 작성합니다.

Java code

import java.util.*;

public class OptionalChaining {
    record Address(String city) {}
    record Company(Address address) {}
    record User(String name, Company company) {}

    static Optional<User> findUser(String id) {
        if ("1".equals(id)) {
            return Optional.of(new User("홍길동",
                new Company(new Address("서울"))));
        }
        if ("2".equals(id)) {
            return Optional.of(new User("김철수", null));
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        // flatMap 체이닝으로 null 안전 탐색
        String city = findUser("1")
            .map(User::company)
            .map(Company::address)
            .map(Address::city)
            .orElse("알 수 없음");
        System.out.println(city); // 서울

        // company가 null인 경우
        String city2 = findUser("2")
            .map(User::company)   // Optional.empty() (null이므로)
            .map(Company::address)
            .map(Address::city)
            .orElse("알 수 없음");
        System.out.println(city2); // 알 수 없음

        // or()로 대체 소스 제공
        User user = findUser("999")
            .or(() -> findUser("1"))
            .orElseThrow();
        System.out.println(user.name()); // 홍길동

        // stream()으로 변환 (Java 9+)
        List<String> cities = List.of("1", "2", "3").stream()
            .map(id -> findUser(id))
            .flatMap(Optional::stream) // 비어있으면 제외
            .map(User::name)
            .toList();
        System.out.println(cities); // [홍길동, 김철수]
    }
}

학습 팁

Optional.stream()(Java 9+)을 사용하면 filter(Optional::isPresent).map(Optional::get) 패턴을 깔끔하게 대체할 수 있습니다.

주의할 점

map()은 값이 null이면 자동으로 Optional.empty()를 반환합니다. flatMap()은 반환값이 이미 Optional인 경우에 사용하세요.

자주 묻는 질문

Optional 체이닝란 무엇인가요?

Optional 을 함수형으로 체이닝하여 null 안전한 코드를 작성합니다.

Optional 체이닝 학습 시 주의할 점은 무엇인가요?

map() 은 값이 null이면 자동으로 Optional.empty() 를 반환합니다. flatMap() 은 반환값이 이미 Optional인 경우에 사용하세요.