Collectors — 유용한 리덕션 연산을 구현하는 Collector 구현

Collectors — 유용한 리덕션 연산을 구현하는 Collector 구현

다양한 유용한 리덕션 연산을 구현하는 Collector의 구현을 제공하는 클래스예요. 요소를 컬렉션에 축적하거나, 다양한 기준에 따라 요소를 요약하는 등의 작업을 해요.

출처: Java API Reference

본문

public final class Collectors extends Object

미리 정의된 컬렉터를 사용해 일반적인 가변 리덕션 작업을 수행하는 예시예요:

// 이름을 List에 축적
List<String> list = people.stream()
  .map(Person::getName)
  .collect(Collectors.toList());

// 이름을 TreeSet에 축적
Set<String> set = people.stream()
  .map(Person::getName)
  .collect(Collectors.toCollection(TreeSet::new));

// 요소를 문자열로 변환해 쉼표로 연결
String joined = things.stream()
  .map(Object::toString)
  .collect(Collectors.joining(", "));

// 직원 급여 합계 계산
int total = employees.stream()
  .collect(Collectors.summingInt(Employee::getSalary));

// 부서별로 직원 그룹화
Map<Department, List<Employee>> byDept = employees.stream()
  .collect(Collectors.groupingBy(Employee::getDepartment));

주요 정적 메서드

  • toList() — 입력 요소를 새 List에 축적하는 Collector를 반환해요.

  • toSet() — 입력 요소를 새 Set에 축적하는 Collector를 반환해요.

  • toCollection(Supplier) — 요소를 제공된 컬렉션 타입에 축적하는 Collector를 반환해요.

  • toMap(...) — 키와 값을 매핑 함수로 생성해 Map에 축적하는 Collector를 반환해요.

  • joining(...) — 입력 요소를 구분자로 구분해 연결한 String을 만드는 Collector를 반환해요.

  • summingInt(...) / summingLong(...) / summingDouble(...) — 매핑 함수를 적용한 값의 합을 만드는 Collector를 반환해요.

  • averagingInt(...) / averagingLong(...) / averagingDouble(...) — 값의 산술 평균을 만드는 Collector를 반환해요.

  • summarizingInt(...) — count·sum·min·max·average를 담은 요약을 만드는 Collector를 반환해요.

  • groupingBy(...) — 분류 함수에 따라 요소를 그룹으로 분류해 Map으로 만드는 Collector를 반환해요.

  • partitioningBy(Predicate) — 조건에 따라 요소를 두 그룹으로 분할하는 Collector를 반환해요.

  • counting() — 입력 요소 수를 세는 Collector를 반환해요.

  • minBy(Comparator) / maxBy(Comparator) — 최소·최대 요소를 Optional로 생성하는 Collector를 반환해요.

  • 도입 시점(Since): 1.8

더 알아보기 (Learn more)