Collector
1 컬렉터
-
스트림의 최종 연산 collect는 다양한 요소 누적 방식을 인수로 받아서 스트림을 최종 결과로 도출하는 리듀싱 연산을 수행한다
- 다양한 요소 누적 방식은 Collector 인터페이스에 정의가 되어있다
- 즉 Collector 인터페이스란 스트림의 요소를 어떤식으로 도출할지에 대한 명세서이다
-
컬텍터란 Collector 인터페이스 구현체를 말한다
-
스트림의 요소를 어떤식으로 도출할지 그 방식을 Collector 인터페이스 구현에 명시하고 이를 Stream의 collect 메소드에 넘겨준다
-
Stream의 collect를 호출하면 스트림의 요소에 컬렉터로 파라미터화된 리듀싱 연산이 수행된다
2 Collectors 클래스
- Collectors 클래스는 팩토리 메서드를 통해 미리 정의된 컬렉터(Collector 인터페이스의 구현체)를 제공한다
- Collectors에서 제공하는 메서드의 기능은 크게 세 가지로 구분
- 스트림 요소를 하나의 값으로 리듀스하고 요약
- 요소 그룹화
- 요소 분할
예시 코드
public static final List<Dish> menu = asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 400, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH)
);
2.1 counting
@Test
void testCounting() {
Long howManyDishes = menu.stream().collect(Collectors.counting());
assertThat(howManyDishes).isEqualTo(9);
}
reducing으로 같은 동작
@Test
void testCountingUsingReducing() {
Long howManyDishes = menu.stream().collect(Collectors.reducing(0L, e -> 1L, Long::sum));
assertThat(howManyDishes).isEqualTo(9);
}
2.2 maxBy
@Test
void testMaxBy() {
Dish mostCaloriesDish = menu.stream().collect(Collectors.maxBy(Comparator.comparingInt(Dish::getCalories))).get();
assertThat(mostCaloriesDish.getName()).isEqualTo("pork");
}
2.3 minBy
@Test
void testMinBy() {
Dish leastCaloriesDish = menu.stream().collect(Collectors.minBy(Comparator.comparingInt(Dish::getCalories))).get();
assertThat(mostCaloriesDish.getName()).isEqualTo("season fruit");
}
2.4 summingInt
- summingInt는 객체를 int로 매핑하는 함수를 인수로 받는다
- 변환 함수라고 한다
@Test
void testSummingInt() {
int totalCalories = menu.stream().collect(Collectors.summingInt(Dish::getCalories));
assertThat(totalCalories).isEqualTo(4300);
}
2.5 averagingInt
@Test
void testAveragingInt() {
Double avgCalories = menu.stream().collect(Collectors.averagingInt(Dish::getCalories));
System.out.println("avgCalories = " + avgCalories);
}
avgCalories = 477.77777777777777