YJ의 새벽
JAVA ( 스트림의 그룹화,분할 ) 본문
--partitioningBy () : 스트림을 2분할 한다.
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Student{
String name;
boolean isMale; //성별
int hak; //학년
int ban; //반
int score;
Student(String name, boolean isMale , int hak, int ban, int score){
this.name =name;
this.isMale = isMale;
this.hak = hak;
this.ban = ban;
this.score = score;
}
String getName() { return name; }
boolean isMale() { return isMale; }
int getHak() { return hak; }
int getBan() { return ban; }
int getScore() { return score; }
@Override
public String toString() {
return String.format("[%s , %s, %d학년 %d반, %d점]",
name , isMale ? "남" : "여" , hak , ban , score);
}
// groupingBy() 에서 사용 ,, 성적 상 중 하
enum Level { HIGH , MID , LOW }
}
public class Example7 {
public static void main(String[] args) {
Student[] stuArr = {
new Student("김첫째",true, 1, 1, 300),
new Student("김둘째",false, 1, 1, 250),
new Student("김셋째",true, 1, 1, 200),
new Student("김넷째",false, 1, 2, 150),
new Student("김다섯",true, 1, 2, 100),
new Student("김여섯",false, 1, 2, 50),
new Student("김일곱",false, 1, 3, 100),
new Student("김여덟",false, 1, 3, 150),
new Student("김아홉",true, 1, 3, 200),
new Student("김첫째",true, 2, 1, 300),
new Student("김둘째",false, 2, 1, 250),
new Student("김셋째",true, 2, 1, 200),
new Student("김넷째",false, 2, 2, 150),
new Student("김다섯",true, 2, 2, 100),
new Student("김여섯",false, 2, 2, 50),
new Student("김일곱",false, 2, 1, 100),
new Student("김여덟",false, 2, 1, 150),
new Student("김아홉",true, 2, 1, 200)
};
System.out.print("1. 단순분할 ( 성별로 분할 )");
System.out.println();
Map<Boolean, List<Student>> stuBySex = Stream.of(stuArr)
.collect(Collectors.partitioningBy(Student::isMale));
List<Student> maleStudent = stuBySex.get(true);
List<Student> femaleStudent = stuBySex.get(false);
for (Student s : maleStudent) System.out.println(s);
for (Student s : femaleStudent) System.out.println(s);
System.out.println();
System.out.println("2. 단순분할+통계 ( 성별 학생수");
Map<Boolean, Long> stuNumBySex = Stream.of(stuArr)
.collect(Collectors.partitioningBy(Student::isMale, Collectors.counting()));
System.out.println("남학생수 : "+stuNumBySex.get(true));
System.out.println("여학생수 : "+stuNumBySex.get(false));
System.out.println("3. 다중분할(성별 불합격자,100점이하)");
Map<Boolean,Map<Boolean,List<Student>>> failedStuBySex =
Stream.of(stuArr).collect(Collectors.partitioningBy(Student::isMale,
Collectors.partitioningBy( s -> s.getScore() <= 100 )));
List<Student> failedMaleStu = failedStuBySex.get(true).get(true);
List<Student> failedFemaleStu = failedStuBySex.get(false).get(true);
for(Student s : failedMaleStu) System.out.println(s);
for(Student s : failedFemaleStu) System.out.println(s);
}
}
'SelfStudy > JAVA' 카테고리의 다른 글
JAVA 컬렉션 복습 (0) | 2023.04.06 |
---|---|
JAVA ( 스트림 ) (0) | 2023.02.10 |
JAVA ( 메서드참조 ) (0) | 2023.02.09 |
JAVA ( 함수형인터페이스 ) (0) | 2023.02.09 |
JAVA ( 람다식 ) (0) | 2023.02.09 |
Comments