Ch14-45~49. collect()...
0. 목차
Chapter14. 람다와 스트림
Ch14 - 45. collect()와 Collectors
Ch14 - 46. 스트림을 컬렉션, 배열로 변환
Ch14 - 47. 스트림의 통계 : counting()…
Ch14 - 48. 스트림을 리듀싱 : reducing()
Ch14 - 49. 스트림을 문자열로 결합 : joining()
Ch14 - 45. collect()와 Collectors
▶ collect()
최종 연산
▷ collect()
와 reduce()
collect()
: 전체 reducingreduce()
: 그룹별 reducing
▷ Collector
를 매개 변수로 하는 스트림의 최종 연산
Object collect(Collector collector) // Collector(인터페이스)를 구현한 클래스의 객체를 매개 변수로 사용
Object collect(Supplier, BiConsumer accumulator, BiConsumer combiner) // Collector 중에서도 지정하여 사용, 잘 사용X
▶ Collector
인터페이스
▷ 수집(collect)에 필요한 메서드를 정의 해 놓은 인터페이스
public interface Collector<T, A, R> { // 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<Characteristics> chracteristics(); // 컬렉터의 특성이 담긴 set을 반환
...
}
▷ 이렇게 구현한 Collector
를 collect()
의 매개 변수로 사용
Object collect(Collector collector)
▷ Collector
를 직접 구현하여 사용해야 하나?
- Nope!
Collecors
클래스를 제공하여 줌
▶ Collectors
클래스
▷ 다양한 기능의 컬렉터(Collector
를 구현한 클래스)를 제공
변환 : mapping(), toList(), toSet(), toMap(), toCollection() ...
통계 : counting(), summingInt(), averagingInt(), maxBy(), minBy(), summarizingInt()...
문자열 결합 : joining()
reducing : reducing()
그룹화와 분활 : groupingBy(), partitioningBy(), collectingAndThen()
Ch14 - 46. 스트림을 컬렉션, 배열로 변환
▶ 스트림 → 컬렉션 : toList(), toSet(), toMap(), toCollection()
▷ toList()
List<String> names
= stuStream
.map(Student::getName) // Stream<Strudent> → Stream<String>
.collect(Collectors.toList()); // Stream<String> → List<String>
▷ toCollection()
ArrayList<String> list
= names
.stream()
.collect(Collectors.toCollection(ArrayList::new)); // Stream<String> → ArrayList<String>
▷ toMap()
Map<String, Person> map
= personStream
.collect(Collectors.toMap(p -> p.getRegId(), p -> p)); // Stream<Person> → Map<String, Person>
▶ 스트림 → 배열 : toArray()
▷ toArray()
Student[] stuNames = studentStream.toArray(Student[]::new); // OK
Student[] stuNames = studentStream.toArray(); // ERROR, 자동 형변환X
Student[] stuNames = (Student[])studentStream.toArray(); // OK, 수동 형변환O
Object[] stuNames = studentStream.toArray(); // OK
Ch14 - 47. 스트림의 통계 : counting()…
▶ 스트림의 통계 정보 제공 : counting(), summingInt(), maxBy(), minBy()…
▷ counting()
// 전체 count
long count = stuStream.count();
// 그룹별 count
// 그룹 지정하지 않으면 전체 count
long count = stuStream.collect(counting()); // Collectors.counting()
▷ summingInt()
// 전체 sum
long totalScore = stuStream.mapToInt(Student::getTotalScore).sum();
// 그룹별 sum
// 그룹 지정하지 않으면 전체 sum
long totalScore = stuStream.collect(summingInt(Student::getTotalScore));
▷ maxBy()
// 최대값
OptionalInt topScore = studentStream.mapToInt(Student::getTotalScore).max();
// 전체 max
Optional<Student> topStudent
= stuStream
.max(Comparator.comparingInt(Student::getTotalScore));
// 그룹별 max, 예를 들어 남자 1등 구할 때 사용
// 그룹 지정하지 않으면 전체 sum
Optional<Student> topStudent
= stuStream
.collet(maxBy(Comparator.comparingInt(Student::getTotalScore)));
Ch14 - 48. 스트림을 리듀싱 : reducing()
▶ Collectors.reducing()
▷ 스트림을 reducing
Collector reducing(BinaryOperator<T> op)
Collector reducing(T identity, BinaryOperator<T> op) // 누적 작업(accumulator)
Collector reducing(U identity, Function<T, U> mapper, BinaryOperator<U> op) // T → U 변환이 필요할 때, map + reduce
▶ Collectors.reducing()
vs reduce()
▷ reduce()
: 전체 reducing
▷ Collectors.reducing()
: 그룹별 reducing
▷ 예시
IntStream intStream = new Random().ints(1, 46).distinct().limit(6);
// 전체 reducing
OptionalInt max = intStream.reduce(Integer::max);
// 그룹별 reducing
OptionalInt<Integer> max = intStream.boxed().collect(reducing(Integer::max);
// 전체 reducing
long sum = intStream.reduce(0, (a, b) -> a + b);
// 그룹별 reducing
long sum = intStream.boxed().collect(reducing(0, (a, b) -> a + b));
// 전체 reducing
int grandTotal = stuStream.map(Student::getTotalScore).reduce(0, Integer::sum);
// 그룹별 reducing
int grandTotal = stuStream.collect(reducing(0, Student::getTotalScore, Integer::sum));
Ch14 - 49. 스트림을 문자열로 결합 : joining()
▶ Collectors.joining()
▷ 문자열 스트림의 요소를 모두 연결
▷ Stream<Student> → Stream<String>
String studentNames = stuStream.map(Student::getName).collect(joing());
String studentNames = stuStream.map(Student::getName).collect(joing(",")); // a, b, c
String studentNames = stuStream.map(Student::getName).collect(joing(",", "[", "]")); // [a, b, c]
String studentNames = stuStream.collect(joining(",")); // Student의 toString()으로 결합