관리 메뉴

민우의 코딩노트

스트림의 그룹화와 분할 본문

Book/자바의 정석 - 기초편

스트림의 그룹화와 분할

미미누 2024. 1. 1. 01:52

https://www.youtube.com/watch?v=VUh_t_j9qjE&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp&index=171

 

본 강의는 위 강의를 듣고 정리를 진행했습니다.

 


  • partitioningBy()는 스트림을 2분할 한다.
  • groupingBy()는 스트림을 n분할 한다.
Collector partitioingBy(Predicate predicate)

Map<Boolean, List<Student>> stuBySex = stuStream.collect(paritioingBy(Student::isMale));
List<Student> maleStudent = stuBySex.get(true);
List<Student> femaleStudent = stuBySex.get(false);

Map<Boolean, Long> stuNumBySex = stuStream.collect(partitioningBy(Student::isMale, counting()));
Long maleCount = stuBySex.get(true);
List femaleCount = femaleStudent = stuBySex.get(false);

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

// 다중 분할
Map<Boolean, Map<Boolean, List<Student>>> failedStuBySex = stuStream // 다중 분할
.collect(partitioningBy(Student::isMale, paritioningBy(s -> s.getScore() < 150))); // 성별, 성적 분할

List<Student> failedMaleStu = failedStuBySex.get(true).get(true);

  • 스트림의 그룹화 - groupingBy()
  • 스트림의 요소를 그룹화
Collector groupingBy(Function classifier)

Map<Integer, List<Student>> stuByBan = stuStream.collect(groupingBy(Student::getBan, toList()));
// 학생 반별 그룹화 toList 생략 가능

// 다중 그룹화 1. 학년 그룹화 2. 반별 그룹화
Map<Integer, Map<Integer, List<Student>>> stuByHakAndBan = stuStream.collect(
		groupingBy(Student::getHak, groupingBy(Student::getBan)));

Map<Integer, Map<Integer, Set<Student.Level>>> stuByHakAndBan = stuStream
	.collect(
			groupingBy(Student::getHak, groupingBy(Student::getBan,
				mapping(s -> {   // 성적 등급으로 변환(level)
						if (s.getScore() >= 200) return Student.Level.HIGH;
						else if(s.getScore() >= 100) return Student.Level.MID;
						else return Student.Level.LOW;
				}, toSet()) // mapping // enum Level {HIGH, MID, LOV}}
	)) // GROUPING BY
}; // collect()