Cronex
스트림의 그룹화와 분할 본문
스트림의 그룹화와 분할
pratitioningBy()는 스트림을 2분할 한다.
Collector partitioningBy(Predicate predicate)
Collector partitioningBy(Predicate predicate, Collector downstream)
groupingBy()는 스트림을 n분할한다.
Collector groupingBy(Function classifier)
Collector groupingBy(Function classifier, Collecotr downstream)
Collector groupingBy(Function classifier, Supplier mapFactory, Collector downstream)
스트림의 분할 - partitioningBy()
스트림의 요소를 2분할
Map<Boolean, List<Student>> stuBySex = stuStream.collect(partitioningBy(Student::isMale)) //학생들을 성별로 분할
List<Student> maleStudent = stuBySex.get(true); //Map에서 남학생 목록을 얻는다.
List<Student> femaleStudent = stuBySex.get(false); //Map에서 여학생 목록을 얻는다.
Map<Boolean, Long> stuNumBySex = stuStream.collect(partitioningBy(Student::isMale, counting())) // 분할 + 통계 (Collectors)
System.out.println("남학생 수 : " + stuNumBySex.get(true)); //남학생 수
System.out.println("여학생 수 : " + stuNumBySex.get(false)) //여학생 수
Map<Boolean, Optional<Student>> topScoreBySex = stuStream.collect(partitioningBy(Student::isMale, maxBy(ComparingInt(Student::getScore)));
System.out.println("남학생 1등 : " + topScoreBySex.get(true)) //남학생 1등 : Optional[[나자바, 남, 1, 1, 300]]
System.out.println("여학생 1등 : " + topScoreBySex.get(false)) // 여학생 1등 : Optional[[기미짐, 여, 1,1, 250]]
failedStuBySex = stuStream.collect(partitioningBy(Student::isMale), partitioningBy(s -> s.getScore < 150))
List<Student> failedMaleStu = failedStuBySex.get(true).get(true); //불합격
List<Student> failedFemaleStu = failedStuBySex.get(false).get(true);'
'JAVA > JAVA의 정석' 카테고리의 다른 글
java - Optional<T> (0) | 2021.07.22 |
---|---|
스트림 (0) | 2021.07.21 |
메서드 참조 (0) | 2021.07.21 |
java- 람다식(Lambda expression) (0) | 2021.07.20 |
package와 import (0) | 2021.07.20 |