기준
숫자 합계는 mapToInt(...).sum()으로 구한다. 제출 호환성이 걱정되면 stream().toList()보다 collect(Collectors.toList())를 쓴다.
Collection Integer 합계
Collection<Integer>나 List<Integer>의 합은 다음처럼 구한다.
int total = values.stream()
.mapToInt(Integer::intValue)
.sum();
Map의 value 합계도 같다.
int total = map.values().stream()
.mapToInt(Integer::intValue)
.sum();
int 배열 합계
int[]는 Arrays.stream을 쓴다.
int total = Arrays.stream(arr).sum();
객체 배열 Integer[]는 한 번 더 변환한다.
int total = Arrays.stream(arr)
.mapToInt(Integer::intValue)
.sum();
comparator 안에서 sum 호출
정렬 중 comparator는 여러 번 호출된다. 따라서 comparator 안에서 합계를 구하면 같은 계산이 반복될 수 있다.
list.sort((a, b) -> {
int aSum = a.values().stream().mapToInt(Integer::intValue).sum();
int bSum = b.values().stream().mapToInt(Integer::intValue).sum();
return Integer.compare(bSum, aSum);
});
입력이 작으면 통과할 수 있지만, 더 안정적인 방식은 합계를 미리 저장하는 것이다.
Map<String, Integer> total = new HashMap<>();
for (int i = 0; i < genres.length; i++) {
total.put(genres[i], total.getOrDefault(genres[i], 0) + plays[i]);
}
toList와 Collectors.toList
Stream.toList()는 Java 16 이후 API다.
List<Integer> list = stream.toList();
채점 환경이나 컴파일 타깃이 낮으면 인식되지 않을 수 있다. 이때는 Collectors.toList()를 사용한다.
import java.util.stream.Collectors;
List<Integer> list = stream.collect(Collectors.toList());
프로그래머스 제출에서는 Collectors.toList()가 더 안전한 선택일 때가 있다.
외우는 표
| 대상 | 합계 코드 |
|---|---|
int[] | Arrays.stream(arr).sum() |
Integer[] | Arrays.stream(arr).mapToInt(Integer::intValue).sum() |
List<Integer> | list.stream().mapToInt(Integer::intValue).sum() |
Collection<Integer> | collection.stream().mapToInt(Integer::intValue).sum() |
Map<K, Integer> values | map.values().stream().mapToInt(Integer::intValue).sum() |
실수 체크
-
sum()을 쓰기 전에IntStream으로 바꿨는가 - comparator 안에서 같은 합계를 반복 계산하고 있지 않은가
- 제출 환경이 애매할 때
Collectors.toList()를 썼는가 -
Collectorsimport를 추가했는가