Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 |
Tags
- 이륜차 교육
- 잠 잘오는 법
- 건강
- 괴산놀거리
- 찬용티비 구독점 ㅋ
- 워터피아
- 노화예방
- 바이크입문 #CB125R #혼다CB125R #125cc추천 #네이키드바이크 #중고바이크 #청주바이크
- 네트워크
- 면역력
- 비타민C
- 데이터 통신과 컴퓨터 네트워크
- 물놀이
- 중원대
- 수면
- 식습관
- 잠 잘자는법
- 괴산
- 데이터 통신과 컴퓨터 네트워크 답
- 수면의 중요성
- 항산화
- 로ㅓ
- 충청도
- 잠자기
- 앙 기모띠 ㅋ
- 가족여행
- 워터파크
- 쉽게 배우는 데이터 통신과 컴퓨터 네트워크
- 한국교통안전공단
- 이륜차
Archives
- Today
- Total
chanYongYong
[Java] Stream API 활용한 그룹화, 조건 분할 (groupingBy(), partitioningBy()) 본문
언어/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 각각 저장한다.
'언어 > Java' 카테고리의 다른 글
| [Java] ENUM (0) | 2026.01.24 |
|---|---|
| [Java] map과 flatMap의 차이점 (0) | 2026.01.23 |