Optional 주요 메서드 정리

 1. 생성 관련

메서드설명
Optional.of(T value) 절대 null이 아닌 값을 감싸는 Optional 생성. null이면 예외 발생
Optional.ofNullable(T value) 값이 null이든 아니든 Optional 생성. null이면 빈 Optional 반환
Optional.empty() 비어 있는 Optional 반환
 
Optional<String> opt1 = Optional.of("abc");  // 정상
Optional<String> opt2 = Optional.ofNullable(null); // Object empty 
Optional.empty() Optional<String> opt3 = Optional.empty(); // 명시적 빈값

 2. 값 조회 관련

메서드설명
get() 값이 있으면 반환, 없으면 NoSuchElementException 발생 ⇒ 비추천
isPresent() 값이 존재하면 true
isEmpty() 값이 없으면 true (Java 11+)
orElse(T other) 값이 있으면 그 값, 없으면 기본값 반환
orElseGet(Supplier) 값이 있으면 그 값, 없으면 Supplier의 결과 반환
orElseThrow() 값이 있으면 그 값, 없으면 NoSuchElementException
orElseThrow(Supplier) 값이 없으면 커스텀 예외 발생
 
Optional<String> opt = Optional.ofNullable(null); 

String result = opt.orElse("default"); // "default"
String result2 = opt.orElseGet(() -> "computed"); // "computed"
String result3 = opt.orElseThrow(() -> new IllegalStateException("값 없음"));

 3. 조건 처리 및 변환

메서드설명
ifPresent(Consumer) 값이 있으면 Consumer 수행
ifPresentOrElse(Consumer, Runnable) 값이 있으면 Consumer, 없으면 Runnable 수행 (Java 9+)
filter(Predicate) 조건에 맞으면 유지, 아니면 Optional.empty()
map(Function) 값을 다른 값으로 변환
flatMap(Function) Optional 안의 Optional 방지용 map
opt.ifPresent(value -> System.out.println(value));

String len = Optional.of("abc")
					.map(String::length) // map: 3 
					.map(Object::toString) // "3" 
					.orElse("0");
 

 

 

 Optional 사용 시 주의사항

  • Optional.get()은 사용 지양. 반드시 존재 보장 시만 사용
  • null 체크 대체용으로 메서드 리턴 타입에 주로 사용
  • 필드나 생성자/세터 인자에는 Optional을 쓰지 말 것 (권장 X, 성능과 직관성 저하)

'끄적 > BE' 카테고리의 다른 글

Spring Security  (0) 2023.07.18
TCP UDP  (0) 2023.02.05
Servlet  (0) 2023.01.18
JPA vs MyBatis  (0) 2023.01.11
JPA N+1  (0) 2023.01.11

+ Recent posts