728x90
Optional 클래스
java.util.Optional<T>
- Optional은 선택형 값을 캡슐화 하는 클래스 입니다.
- 값이 있으면 Optional 클래스는 값을 감쌉니다.
- 값이 없으면 Optional.empty 메서드로 Optional을 반환 합니다.
값이 없을경우 디폴트 값을 설정하거나 집계값을 처리하는 Consumer로 등록할 수 있습니다.

최종 처리에서 average 사용시 요소 없는 경우를 대비하는 방법
- isPresent() 메서드가 true를 리턴 할때만 집계값을 얻습니다.
- orElse() 메서드로 집계값이 없을 경우를 대비해서 디폴트 값을 정해 놓습니다.
- ifPresent() 메서드로 집계깞이 있을 경우에만 동작하는 Consumer 람다식을 제공합니다.
1) isPresent() 메소드가 true를 리턴할 때만 집계값을 얻습니다.
OptionalDouble optional = stream
.average();
if(optional.isPresent()) {
System.out.println("평균: " + optional.getAsDouble());
} else {
System.out.println("평균: 0.0" );
}
2) orElse() 메소드로 집계값이 없을 경우를 대비해서 디폴트 값을 정해놓습니다.
double avg = stream
.average()
.orElse(0.0);
System.out.println("평균 : " + avg);
3) ifPresent() 메소드로 집계값이 있을 경우에만 동작하는 Consumer 람다식을 제공합니다.
stream
.average()
.ifPresent(a -> System.out.println("평균: " + a);
OptionalExam.java
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalDouble;
public class OptionalExam {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
// 예외 발생 (java.util.NoSuchElementException)
// double avg = list.stream()
// .mapToInt(Integer :: intValue)
// .average()
// .getAsDouble();
// 값이 없을 경우 처리하는 3가지 방법
// 방법 1: isPresent()
OptionalDouble optional = list.stream()
.mapToInt(Integer :: intValue)
.average();
if(optional.isPresent()) {
System.out.println("방법1_평균: " + optional.getAsDouble());
}else {
System.out.println("방법1_평균: 0.0");
}
// 방법 2: orElse() - default 값을 출력
double avg = list.stream()
.mapToInt(Integer :: intValue)
.average()
.orElse(0.0);
System.out.println("방법2_평균: " + avg);
// 방법 3: ifPResent - 값이 있으면 동작
list.stream()
.mapToInt(Integer :: intValue)
.average()
.ifPresent(a -> System.out.println("방법3_평균: " + a));
}
}
결과 :
방법1_평균: 0.0
방법2_평균: 0.0
tip)
Optional은 선택형 값을 캡슐화 하는 클래스 입니다.
값이 있을때 Wrapper Class 형태로 감싸게 됩니다.
자료형(기본타입) -> 래퍼클래스 (Wrapper class)
byte -> Byte
short -> Short
int -> Integer
long -> Long
double -> Double
float -> Float
char -> Character
boolean -> Boolean
기본타입의 데이터를 객체로 취급해야 하는 경우
메서드의 인수로 객체 타입 만이 요구되며, 기본 타입의 데이터를 그대로 사용할수 없을때,
기본타입의 데이터를 객체로 변환한 후 작업을 수행해야 합니다.
728x90
'JAVA > Java 기초' 카테고리의 다른 글
| 입출력 스트림-2.java (0) | 2023.01.30 |
|---|---|
| 입출력 스트림.java (0) | 2023.01.30 |
| 루핑, 매칭, 집계.java (0) | 2023.01.30 |
| 정렬. java (0) | 2023.01.30 |
| 람다식.java (0) | 2023.01.27 |