티스토리 뷰

Backend/Java8

#28 Advanced Stream - Collectors

RadderNepa 2022. 10. 17. 00:42

● 도입

1. Collectors - collect / toList / toSet

<R, A> R collect(Collector<? super T, A, R> collector);

java.util.stream.Collectors
Collector<T, ?, List<T>> toList();
Collector<T, ?, Set<T>> toSet();

Collectors
- 자주 쓰일법한 유용한 collector들을 모아놓은 util class
- java.util.stream 패키지에서 제공한다.

collect
- 주어진 collector를 이용해 Stream 안의 데이터를 합친다.
- 일반적으로 특정 data structure로 데이터를 모을 때 사용한다.

toList
- Stream 안의 데이터를 List 형태로 반환해주는 collector

toSet
- Stream 안의 데이터를 Set 형태로 반환해주는 collector
- Set이기 때문에 중복값은 사라지고 순서가 무의미해진다.

 

2. Collectors - mapping / reducing

public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper
                                                                                    , Collector<? super U, A, R> downstream)

public static <T> Collector<T, ?, T> reducing(T identity, BinaryOperator<T> op)

mapping
- map method와 collect를 합쳐놓은 역할을 해주는 collector
- 일반적으로 map method를 적용한 후 collect를 해도 되지만 groupingBy 등 필요한 때가 있다.

reducing
- reduce를 해주는 collector

* 이외에도 filtering, flatMapping, counting, minBy, maxBy 등도 있다.

 

 

● 실습

package com.fastcampus.functionalprogramming.chapter8;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Chapter8Section5 {
	public static void main(String[] args) {
		// 1. List : 순서 O, 중복 허용 O
		List<Integer> numberList = Stream.of(3, 5, -3, 3, 4, 5).collect(Collectors.toList());
		System.out.println("1 : " + numberList);	// [3, 5, -3, 3, 4, 5]
// ===================================================================================================
		// 2. Set : 순서 X, 중복 허용 X
		Set<Integer> numberSet = Stream.of(3, 5, -3, 3, 4, 5).collect(Collectors.toSet());
		System.out.println("2 : " + numberSet);		// [-3, 3, 4, 5]
// ===================================================================================================
		// 3. mapping to List
		// TODO : 절댓값을 적용시켜보자
		List<Integer> numberList2 = Stream.of(3, 5, -3, 3, 4, 5).collect(Collectors.mapping(x -> Math.abs(x), Collectors.toList()));
		System.out.println("3 : " + numberList2);	// [3, 5, 3, 3, 4, 5]
		/*
		 * mapping(x -> Math.abs(x), Collectors.toList())의 순서
		 * 
		 * 1. x -> Math.abs(x) 	  : Stream 안의 Integer 들을 절댓값으로 바꾼다.
		 * 2. Collectors.toList() : 절댓값으로 바뀐 데이터들을 List에 담는다.
		 * 
		 * - map이 먼저 적용된 후 그 결과값이 List에 담기는 것이다.
		 * - 즉, map method와 Collectors.toList()를 따로따로 호출해서 적용시키는 것과 동일한 결과가 나오는 것이다.
		 */
// ===================================================================================================
		// 4. mapping to Set
		// TODO : 절댓값을 적용시켜보자
		Set<Integer> numberSet2 = Stream.of(3, 5, -3, 3, 4, 5).collect(Collectors.mapping(x -> Math.abs(x), Collectors.toSet()));
		System.out.println("4 : " + numberSet2);	// [3, 4, 5]
// ===================================================================================================
		// 5. reducing
		// TODO : 전체 합을 구하자
		Integer sum = Stream.of(3, 5, -3, 3, 4, 5).collect(Collectors.reducing(0, (x, y) -> x + y)); // 초기값은 '0'으로 제공
		System.out.println("5 : " + sum);			// 17
	}
}

'Backend > Java8' 카테고리의 다른 글

#30 Advanced Stream - Grouping By  (1) 2022.10.19
#29 Advanced Stream - To Map  (0) 2022.10.18
#27 Advanced Stream - Reduce  (0) 2022.10.16
#26 Advanced Stream - Find First / Find Any  (1) 2022.10.15
#25 Advanced Stream - All Match / Any Match  (0) 2022.10.14
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/11   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함