언어/Java
[Java] Stream API 활용한 그룹화, 조건 분할 (groupingBy(), partitioningBy())
chanYongYong
2026. 1. 25. 22:10
Stream API에서 colect()와 groupingBy(), partitioningBy()를 활용하면 그룹화와 조건 분할이 가능하다.
업무 중 필요한 데이터 대시보드화 해 리포트, 통계를 적용하려면 이 함수들을 알아야 한다. (사실 이럴 땐 자바보단 파이썬을....)
groupingBy() 사용 예시 3가지
groupingBy()의 반환타입은 map< 그룹키,list<T>>이다.
다음 3가지 예시를 보며 사용법을 익혀보자.
단순 그룹화
// 학년별로 그룹화 (Student 객체 전체 저장)
Map<Integer, List<Student>> gradeMap = studentList.stream()
.collect(Collectors.groupingBy(Student::getGrade));
// {1=[Student객체들...], 2=[Student객체들...], 3=[Student객체들...]}
그룹화 + 매핑 (객체의 특정 필드만 추출가능)
// 학년별로 그룹화 + 이름만 추출
Map<Integer, List<String>> gradeNameMap = studentList.stream()
.collect(Collectors.groupingBy(
Student::getGrade,
Collectors.mapping(Student::getName, Collectors.toList())
));
// {1=[홍길동, 이순신, 문성실], 2=[강감찬, 심사임당], 3=[유관순]}
다중 레벨 그룹화
// 학년별로 그룹화 → 그 안에서 성별로 다시 그룹화
Map<Integer, Map<String, List<Student>>> gradeAndGenderMap = studentList.stream()
.collect(Collectors.groupingBy(
Student::getGrade,
Collectors.groupingBy(Student::getGender)
));
// {1={남=[홍길동, 이순신], 여=[문성실]}, 2={남=[강감찬], 여=[심사임당]}, 3={여=[유관순]}}
partitioningBy()
partitioningBy()는 Predicate(조건)을 기준으로 true/false 두 그룹으로 분할한다.
명확하게 참 거짓 나눌 때 사용한다.
// filter() - 조건에 맞는 것만 반환, 나머지는 버려짐
List<Student> passed = studentList.stream()
.filter(s -> s.getScore() >= 90)
.collect(Collectors.toList());
// 결과: 90점 이상만 얻음 (미만은 접근 불가)
// partitioningBy() - true/false 양쪽 모두 Map에 보관
Map<Boolean, List<Student>> result = studentList.stream()
.collect(Collectors.partitioningBy(s -> s.getScore() >= 90));
result.get(true); // 90점 이상
result.get(false); // 90점 미만
filter()와 partitioningBy()의 차이점
filter()는 반환타입이 Stream이고 조건에 만족하지 않는 데이터는 걸러낸다.
partitioningBy()는 반환타입이 Map이고 조건에 만족하지 않는 데이터도 포함해서 true, false 각각 저장한다.