Language/Java
Java Stream Collector
kimjingyu
2023. 4. 7. 16:38
728x90
그룹화
스트림 사용 이후에 처리하기 조금 더 편리한 형태 즉, 내가 원하는 자료 구조로 그룹화 시킬 수 있다.
groupingBy
- 전체 직원(Users)에서 직책(Position)별로 나눠서 직원을 그룹화
Map<User.Position, List<User>> usersByPosition =
users.stream()
.collect(groupingBy(User::getPosition));
- 결과
- groupingBy의 파라미터로 온 분류함수를 기준에 의해 Map의 key로가고 객체들은 value로 그룹화되었다.
{MANAGER=[tony, alex, oliveia], STAFF=[elsa, mayya, lily, jacob, jace], CEO=[eric]
2. 여러 조건에 의해서 분류
- 직책별로 우수사원을 뽑기위해 groupingBy의 오버라이드 메소드를 이용한다.
- User::getPosition으로 직책으로 분리를 우선하고, filtering 즉 프레디케이트(predicate) 조건을 갖는 Collector를 이용하여 필터링된 객체를 다시 그룹화합니다.
Map<User.Position, List<User>> excellentUsersByPosition =
users.stream()
.collect(groupingBy(User::getPosition,
filtering(user -> user.getScore() > 100, toList())));
- 결과
{MANAGER=[tony], STAFF=[lily, jacob], CEO=[]}
3. mapping 도 있다. (둘 다 Collector)
- 객체로 그룹화하는게 아니라 다른 타입으로 매핑한다.
Map<User.Position, List<User>> excellentUserAgeByPosition =
users.stream()
.collect(groupingBy(User::getPosition,
mapping(User::getAge, toList())));
- 결과
{MANAGER=[39,37,37], STAFF=[29, 33, 33, 31, 37], CEO=[55]}
flatMapping 도 있다.
인용
https://jeong-pro.tistory.com/229
Java Stream Collector 반쪽짜리 스트림을 쓰던 그대에게. Advanced Stream!
Java Stream "Collector" filter, map, reduce, ... 뭐 이 정도? 이번에 "모던 자바 인 액션"이라는 책을 다시 보면서 반쪽짜리 스트림을 쓰고 있었구나... 하는 생각이 들었습니다. 이전에는 filter, map, reduce, flat
jeong-pro.tistory.com
728x90