반응형
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalDouble;
public class Example {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
/*요소가 없기때문에에외 발생 NoSuchElementException: No value present
double avg=list.stream()
.mapToInt(Integer::intValue)
.average()
.getAsDouble();
*/
//요소가 없을 경우에 예외를 피하는 3가지 방법
//1번째 Optional 객체를 얻어 isPresent()로 평균값여부확인
OptionalDouble optionalDouble = list.stream().mapToInt(Integer::intValue).average();
if (optionalDouble.isPresent()) {
System.out.println("1. 평균" + optionalDouble);
} else {
System.out.println(0.0);
}
//2번째 방법 orElse() 메소드로 디폴드값정하기
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. 평균" + avg));
}
}
반응형