[Java] Optional 사용법

Java 2021. 2. 19. 08:02

- @참고: www.daleseo.com/java8-optional-effective/

- @참고(Optional java doc): docs.oracle.com/javase/8/docs/api/java/util/Optional.html

 

Optional 변수 선언하기

Optional.empty() //null을 담은 빈 Optional 객체
Optional.of(value) //null이 아닌 객체를 담고 있는 Optional 객체를 생성. null이 넘어올 경우 NPE 던짐
Optional.ofNullable(value) //null인지 아닌지 확신할 수 없는 객체를 담고 있는 Optional 객체를 생성

 

Optional이 담고 있는 객체 접근하기

get() //비어있는 Optional 객체에 대해서, NoSuchElementException을 던짐
orElse(T other) //비어있는 Optional 객체에 대해서, 넘어온 인자를 반환
orElseGet(Supplier<? extends T> other) //비어있는 Optional 객체에 대해서, 넘어온 함수형 인자를 반환. 비어있는 경우만 함수가 호출되므로 orElse 대비 성능상 이점이 있음
orElseThrow(Supplier<? extends X> exceptionSupplier) //비어있는 Optional 객체에 대해서, 넘어온 함수형 인자를 통해 생성된 예외를 던짐

 

Optional의 활용 메소드

Optional<T> filter(Predicate<? super T> predicate) //If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
Optional<T> map(Function<? super T, extends U> mapper) //If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.

void ifPresent(Consumer<? super T> consumer) //If a value is present, invoke the specified consumer with the value, otherwise do nothing.
boolean isPresent() //Return true if there is a value present, otherwise false.

boolean equals(Object obj) //Indicates whether some other object is "equal to" this Optional.

 

Optional 활용 코드 샘플

int length = Optional.ofNullable(getText()).map(String::length).orElse(0);

/* 주문을 한 회원이 살고 있는 도시를 반환한다 */
public String getCityOfMemberFromOrder(Order order) {
	return Optional.ofNullable(order)
			.map(Order::getMember)
			.map(Member::getAddress)
			.map(Address::getCity)
			.orElse("Seoul");
}

/* 주어진 시간(분) 내에 생성된 주문을 한 경우에만 해당 회원 정보를 구한다 */
public Optional<Member> getMemberIfOrderWithin(Order order, int min) {
	return Optional.ofNullable(order)
			.filter(o -> o.getDate().getTime() > System.currentTimeMillis() - min * 1000)
			.map(Order::getMember);
}

/* List 로부터 주어진 인덱스에 해당하는 값을 담은 Optional 객체를 반환한다. */
public static <T> Optional<T> getAsOptional(List<T> list, int index) {
	try {
		return Optional.of(list.get(index));
	} catch (ArrayIndexOutOfBoundsException e) {
		return Optional.empty();
	}
}

Optional<String> maybeCity = getAsOptional(cities, 3); // Optional
maybeCity.ifPresent(city -> {
	System.out.println("length: " + city.length());
});

'Java' 카테고리의 다른 글

[Java] LocalDateTime, Timestamp 변환  (0) 2021.02.26
[Java] Set to List, List to Set  (0) 2021.02.25
[Java] 파일 입출력  (0) 2021.01.27
[java] url 주소 가져오기  (0) 2020.11.11
Interface Comparable vs Interface Comparator  (0) 2020.01.07
블로그 이미지

uchacha

개발자 일지

,