본문 바로가기

Knowledge Wiki/Java

JAVA 스트림 그룹화, 분할 - partitioningBy(), groupingBy()

1. 스트림의 그룹화와 분할
    partitioningBy()는 스트림을 2 분할한다. groupingBy()보다 빠르다.
    groupingBy()는 스트림을 n분할한다.

Map<Boolean, List<Student>> stuBySex = stuStream.collect(partitioningBy(Student::isMale)); // 학생들을 성별로 분할
List<Student> maleStudent = stuBySex.get(true); // 남학생 목록
List<Student> femaleStudent = stuBySex.get(false); / /여학생 목록

Map<Boolean, Long> stuNumBySex = stuStream.collect(partitioningBy(Student::isMale, counting())); // 분할 + 통계
int maleCnt = stuNumBySex.get(true); // 남학생 수
int femaleCnt = stuNumBySex.get(false); // 여학생 수

Map<Boolean, Optional<Student>> topScoreBySex = stuStream.collect(partitioningBy(Student::isMale, maxBy(comparingInt(Student::getScore)))); // 분할 + 통계
int maleTopScore = topScoreBySex.get(true); // 남학생 1등
int femaleTopScore = topScoreBySex.get(false); // 여학생 1등

Map<Boolean, Map<Boolean, List<Student>>> failedStuBySex = stuStream.collect(
	partitioningBy(Student::isMale, // 1. 성별로 분할 (남/녀)
		partitioningBy(s -> s.getScore() < 150))); // 2. 성적으로 분할 (불합격/합격)
List<Student> failedMaleStu = failedStuBySex.get(true).get(true); // 첫번째 true - 남자, 두번째 true - 불합격
List<Student> failedFemaleStu = failedStuBySex.get(false).get(true); // 첫번째 true - 여자, 두번째 true - 불합격