(JAVA) IntStream

양찬우·2023년 12월 29일

JAVA

목록 보기
2/3

IntStream의 주요메서드

IntStream은 기본 정수형(int)의 스트림을 다루기 위한 인터페이스

1. range(int startInclusive, int endExclusive), rangeClosed(int startInclusive, int endInclusive):
정수의 범위를 생성합니다.

IntStream.range(1, 5);         // 1, 2, 3, 4
IntStream.rangeClosed(1, 5);   // 1, 2, 3, 4, 5


2. of(int values) : 주어진 값으로 구성된 스트림을 생성합니다.

IntStream.of(1, 2, 3, 4, 5);

3. forEach(IntConsumer action): 각 요소에 주어진 동작을 수행합니다.

IntStream.range(1, 5).forEach(System.out::println);

4. map(IntUnaryOperator mapper): 각 요소에 주어진 함수를 적용하여 값을 변환합니다.

IntStream.range(1, 5).map(x -> x * 2); // 2, 4, 6, 8


5. filter(IntPredicate predicate): 주어진 조건에 따라 스트림의 요소를 필터링합니다.

IntStream.range(1, 10).filter(x -> x % 2 == 0); // 2, 4, 6, 8

6. sum(), min(), max(), average(): 숫자 스트림의 합계, 최솟값, 최댓값, 평균을 계산합니다.

int sum = IntStream.range(1, 5).sum();


7. reduce(int identity, IntBinaryOperator op): 스트림의 요소를 이진 연산자를 사용하여 축소합니다.

int sum = IntStream.range(1, 5).reduce(0, (x, y) -> x + y); // 합계 계산
//x는 현재까지 누산된 값, y는 다음요소, 즉 초기값 0이 x, 1이 y -> 마지막엔 x값이 10, y값이 5 -> 15

8. distinct(): 중복된 요소를 제거합니다.

IntStream.of(1, 2, 2, 3, 3, 4).distinct(); // 1, 2, 3, 4


9. boxed(): IntStream을 Stream로 변환합니다.

IntStream.range(1, 5).boxed(); // Stream<Integer>

10. toArray(): 스트림의 요소를 배열로 변환합니다.

int[] array = IntStream.range(1, 5).toArray();
profile
스스로 비교하지 말자

0개의 댓글