반응형
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example {
public static void main(String[] args) {
List<Student> totalList = Arrays.asList(new Student("홍길동", 10, Student.Sex.MALE),
new Student("김수애", 6, Student.Sex.FEMALE),
new Student("신용권", 10, Student.Sex.MALE),
new Student("박수미", 6, Student.Sex.FEMALE));
//남학생들만 묶어서 List 생성
/*
Stream<Student> totalStream=totalList.stream();
Stream<Student>maleStream=totalStream.filter(s->s.getSex()== Student.Sex.MALE);
Collector<Student,?,List<Student>>collector=Collectors.toList();//리스트에서 student를 수집하는 collector를 얻는다.
List<Student>maleList=maleStream.collect(collector);
*/
// 변수 생략하고 간단하게
List<Student>maleList=totalList.stream().filter(s->s.getSex()== Student.Sex.MALE).collect(Collectors.toList());
maleList.stream().forEach(s->System.out.println(s.getName()));
//여학생들만 필터링해서 별도의 HashSet
/*
Stream<Student>totalStream=totalList.stream();
Stream<Student>femaleStream=totalStream.filter(s->s.getSex()== Student.Sex.FEMALE);
Supplier<HashSet<Student>> supplier = HashSet::new; //새로운 hashset을 공급하는 supplier얻기
Collector<Student,?,HashSet<Student>> collector=Collectors.toCollection(supplier);//suppier가 공급하는 hashset에 student를 수집하는 collector생성
Set<Student>femaleSet=femaleStream.collect(collector); //stream에서 collect 메소드로 student 를 수집해서 hashset을 얻는다
*/
Set<Student>femaleSet=totalList.stream().filter(s->s.getSex()== Student.Sex.FEMALE).collect(Collectors.toCollection(HashSet::new));
}
}
public class Student {
public enum Sex {MALE, FEMALE}
public enum City {Seoul, Pusan}
private String name;
private int score;
private Sex sex;
private City city;
public Student(String name, int score, Sex sex) {
this.name = name;
this.score = score;
this.sex = sex;
}
public Student(String name, int score, Sex sex, City city) {
this(name, score, sex);
this.city = city;
}
public String getName() {
return name;
}
public City getCity() {
return city;
}
public Sex getSex() {
return sex;
}
public int getScore() {
return score;
}
}
반응형
'JAVA' 카테고리의 다른 글
Optional 클래스 (0) | 2022.01.19 |
---|