IntStream은 Java 8부터 추가된 기능으로, int형 데이터 요소를 처리할 수 있는 스트림이다.
IntStream을 사용하면 int형 데이터 요소를 스트림으로 처리할 수 있다.
IntStream에서 사용 가능한 기능
목차
- sum(): IntStream의 모든 요소의 합을 계산합니다.
- average(): IntStream의 모든 요소의 평균을 계산합니다.
- min(): IntStream의 최소값을 반환합니다.
- max(): IntStream의 최대값을 반환합니다.
- filter(): IntStream에서 조건에 맞는 요소만을 추출합니다.
- map(): IntStream의 요소를 다른 값으로 변환합니다.
- sorted(): IntStream의 요소를 정렬합니다.
- map(): IntStream의 요소를 다른 값으로 변환합니다.
- reduce(): IntStream의 요소들을 하나의 값으로 축소합니다.
- boxed(): IntStream을 Stream로 변환합니다.
1.sum(): IntStream의 모든 요소의 합을 계산합니다.
int[] arr = {1, 2, 3, 4, 5};
int sum = Arrays.stream(arr).sum();
System.out.println(sum); // 15
2.average(): IntStream의 모든 요소의 평균을 계산합니다.
int[] arr = {1, 2, 3, 4, 5};
double avg = Arrays.stream(arr).average().getAsDouble();
System.out.println(avg); // 3.0
3.min(): IntStream의 최소값을 반환합니다.
int[] arr = {1, 2, 3, 4, 5};
int min = Arrays.stream(arr).min().getAsInt();
System.out.println(min); // 1
4.max(): IntStream의 최대값을 반환합니다.
int[] arr = {1, 2, 3, 4, 5};
int max = Arrays.stream(arr).max().getAsInt();
System.out.println(max); // 5
5.filter(): IntStream에서 조건에 맞는 요소만을 추출합니다.
int[] arr = {1, 2, 3, 4, 5};
int[] result = Arrays.stream(arr)
.filter(value -> value % 2 == 0)
.toArray();
System.out.println(Arrays.toString(result)); // [2, 4]
6.map(): IntStream의 요소를 다른 값으로 변환합니다.
int[] arr = {1, 2, 3, 4, 5};
int[] result = Arrays.stream(arr)
.map(value -> value * 2)
.toArray();
System.out.println(Arrays.toString(result)); // [2, 4, 6, 8, 10]
7.sorted(): IntStream의 요소를 정렬합니다.
int[] arr = {5, 1, 4, 2, 3};
int[] result = Arrays.stream(arr)
.sorted()
.toArray();
System.out.println(Arrays.toString(result)); // [1, 2, 3, 4, 5]
8.distinct(): IntStream에서 중복된 요소를 제거합니다.
int[] arr = {1, 2, 3, 2, 1};
int[] result = Arrays.stream(arr)
.distinct()
.toArray();
System.out.println(Arrays.toString(result)); // [1, 2, 3]
9.reduce(): IntStream의 요소들을 하나의 값으로 축소합니다.
int[] arr = {1, 2, 3, 4, 5};
int product = Arrays.stream(arr)
.reduce((a, b) -> a * b)
.getAsInt();
System.out.println(product); // 120
10.boxed(): IntStream을 Stream<Integer>로 변환합니다.
int[] arr = {1, 2, 3, 4, 5};
Stream<Integer> stream = Arrays.stream(arr).boxed();
'STUDY' 카테고리의 다른 글
백엔드 입문 프로젝트 클래스(Spring boot) (0) | 2023.05.11 |
---|---|
IntStream (0) | 2023.04.19 |
IntStream(3) (0) | 2023.04.19 |
IntStream(2) (0) | 2023.04.19 |
스프링 강의 (0) | 2023.04.15 |