Stream IntStream.range
[문제]
1부터 20까지의 숫자 중 3의 배수만 필터링하여 합계와 개수를 출력하세요.
[요구사항]
- IntStream.range()로 1~20 생성
- filter()로 3의 배수만 선택
- sum()과 count()로 합계와 개수 구하기
[소스]
import java.util.stream.IntStream;
public class IntStreamRange {
public static void main(String[] args) {
System.out.println("1부터 20까지 중 3의 배수:");
// IntStream.range()로 1~20 범위 생성
long count = IntStream.rangeClosed(1, 20) // 1부터 20까지 포함
.filter(n -> n % 3 == 0) // 3의 배수만
.peek(System.out::println) // 선택된 숫자 출력
.count(); // 개수
// 합계 계산
int sum = IntStream.rangeClosed(1, 20)
.filter(n -> n % 3 == 0)
.sum(); // 합계
System.out.println("개수: " + count);
System.out.println("합계: " + sum);
}
}