최종연산 collect 와 colltors
collect는 인터페이스
collect()는 collectors와 매개변수로 하는 스트림의 최종여산
Object Collect (collect Collector) //collector를 구현한 클래스의 객체를 매개변수로 사용
Object Collect(Supplier supplier , BiConcumer , accmulator , BiConsumer Combine) 잘 쓰지않음.
reduce와 collect의 차이 , 사실 거의 같다.
reduce는 stream 전체요소에 대한 리듀스
collect는 stream 전체요소를 그룹화로 나누어 리듀싱
Colletor는 수집(collect)에 필요한 메서드를 정의해 놓은 인터페이스
public interface Collector<T , A , R> { //T(요소) 를 A 에 누적한 다음 결과를 R로 변환해서 반환
Supplier<A> supplier(); //StringBuilder::new 누적할곳
BiConsumer<A,T> accumulator(); //(sb.s) -> sb.append(s) 누적방법
BinaryOperator<A> Combiner(); //(sb1 . sb2) -> sb1.append(sb2) 결합방법,(병렬)
Function<A,R> finisher(); //sb -> sb.toString() 최종반환
set<Characteristice> characteristice(); // 컬렉션 특성이 담긴 set을 반환
반환한 값을 Supplier에 계속 누적해서 Combiner로 (병렬일때) 합쳐서
finisher로 최종변환 시킨다.
누적방법은 accumulator로 선택한다.
Collectors클래스는 다양한 기능의 컬렉션(collector를 구현한 클래스,)를 제공
변환 - mapping() , toList(), toSet() , toMap() , toCollection()
통계 - counting() , summingInt() , averagingInt() , maxBy() , minBy() , summarizingInt();
문자열 결합 - joining()
리듀싱 - reducing()
그룹화와 분할 - groupingBy() , partitioningBy() , CollectingAndThen()
collect 최종연산 , Collecter인터페이스 , Collectors 구현된 클래스
스트림을 컬렉션 , 배열로 변환
toList(), toSet() , toMap() , toCollection()
List<String> names = stuStream.map(student::getName) //stream<student> -> stream<String>
.collect(collectors.toList()) ; //stream<String> -> list<String>
ArrayList<String> list = names.stream().collect(collectors.toCollection(ArrayList::new))
//stream<string> -> ArrayList<string>
Map<String , Person> map = PersionStream.collect(collections,toMap(p->p.getRegId() , p->p))
//stream<persion> -> map<string.person>
스트림을 배열로 변환 - toArray()
student[] stuNames = studentStream.toArray(student[]::new); //매개변수가 있으면 반환타입이 있다
student[] stuNames = studentStream.toArray() //반환타입 에러 // 매개변수 없음
Object[] stuNames = studentStream.toArray(); // 매개변수가 없을땐 반환타입을 Object로
스트림의 통계 counting() , summingInt() , averagingInt() , maxBy() , minBy() , summarizingInt();
long count = stuStream.count();
long count = stuStream.collect(counting()); //collectors.counting();
long totalScore = stuStream.mapToInt(student::getTotalScore).sum() // IntStream의 sum
long totalScore = stuStream.mapToInt(summingInt(student::getTotalScore));
OptionalInt topScore = studentStream.map.toInt(student::getTotalScore).max()
Optional<student> topStudent = stuStream.max(comparator.comparingInt(student::getTotalScore))
Optional<student> topStudent = stuStream.collect(maxBy(comparator.comparingInt(student::getTotalScore)))
'JAVA' 카테고리의 다른 글
스트림12 스트림의 그룹화 분할 (0) | 2023.03.17 |
---|---|
스트림11 스트림의 collector로 reducing 그룹별 리듀싱 (0) | 2023.03.17 |
스트림9 최종연산 reduce() (0) | 2023.03.16 |
스트림8 최종연산 forEach() (0) | 2023.03.16 |
Optional<T> (0) | 2023.03.16 |