Backend
home
📝

stream 예제 코드 13 - Optional

생성일
2025/01/22 10:39
태그
집계값 없는 경우 대비하는 방법
package com.stream3; import java.util.Arrays; import java.util.OptionalDouble; public class ReductionExample { public static void main(String[] args) { int[] intArr = { 2, 4, 6, 8, 10 }; // 집계값이 없는 경우 대비하는 방법 1 OptionalDouble optAvg = Arrays.stream(intArr).average(); if (optAvg.isPresent()) { System.out.println("평균 : " + optAvg.getAsDouble()); } else { // System.out.println("값이 없습니다."); System.out.println("평균 : " + 0.0); } // 집계값이 없는 경우 대비하는 방법 2 double avg = Arrays.stream(intArr).average().orElse(0.0); System.out.println("평균 : " + avg); System.out.println(); // 집계값이 없는 경우 대비하는 방법 3 Arrays.stream(intArr).average().ifPresent(a -> System.out.println(a)); } }
Java
복사
package com.stream3; import java.util.ArrayList; import java.util.List; import java.util.OptionalDouble; public class ReductionExample2 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); OptionalDouble optAvg = list .stream() .mapToInt(i -> i.intValue()) .average(); // .isPresent() -> 평균 1) : 0.0 if (optAvg.isPresent()) { System.out.println("평균 1) : " + optAvg.getAsDouble()); } else { System.out.println("평균 1) : " + 0.0); } // .orElse() -> 평균 2) : 0.0 System.out.println("평균 2) : " + optAvg.orElse(0.0)); // .ifPresent -> 평균 3) : optAvg.ifPresent(a -> System.out.println("평균 3) : " + a)); } }
Java
복사