๋ฐ์ํ
๐ก reduce()์ collect()์ ์ฐจ์ด
2024.12.17 - [โ ์๋ฐ JAVA/โ ํด๋์ค์ ํจ์ Class & Method] - [JAVA][Stream]์ต์ข ์ฐ์ฐ
์ ์ฒด์ ๋ํ ์ฐ์ฐ์ ํ ๋์๋ reduce()์ฌ์ฉํ๊ณ , collect()๋ ๊ทธ๋ฃน๋ณ๋ก ์ฐ์ฐํ ์ ์๋ค.
collect( Collectors.๋ฉ์๋ )
: Collector๋ฅผ ๋งค๊ฐ๋ณ์๋กํ๋
์คํธ๋ฆผ์ ์ต์ข ์ฐ์ฐ ๋ฉ์๋.
๐ก Collector๋ ์์ง(collect)์ ํ์ํ ๋ฉ์๋๋ฅผ ์ ์ํด ๋์ ์ธํฐํ์ด์ค์ด๋ค.
Stream์ ์์ T๋ฅผ A์ ๋์ ํ ๋ค์ R๋ก ๋ฐํํ๋ค.
๐ก Collectorsํด๋์ค๋ ๋ค์ํ ๊ธฐ๋ฅ์ Collector๋ฅผ ๊ตฌํํ์ฌ ๋ฉ์๋๋ก ์ฌ์ฉํ ์ ์๋ค.
- collect()๋ ๋งค๊ฐ๋ณ์๋ก (Collector)๋ฅผ ๊ตฌํํด ์ฌ์ฉํด์ผ ํ๋ค๋ ํน์ง์ ๊ฐ์ง๋ค.
- ์ด Collector์ธํฐํ์ด์ค๋ฅผ ๋ค์ํ๊ฒ ๊ตฌํํ Collectorsํด๋์ค๋ฅผ ์ฌ์ฉํด
- collect(Collectors.๋ฉ์๋)๋ฅผ ์ฌ์ฉํ๋ฉด ์ฝ๊ฒ ์ฌ์ฉํ ์ ์๋ค.
๐ collect()์ ์ฃผ์๊ธฐ๋ฅ
1. ์ปฌ๋ ์ ์ด๋ ๋ฐฐ์ด๋ก ๋ณํ ๊ฐ๋ฅํ๊ฒ ํด์ค๋ค.
2. ๋ถํ ๋ ์คํธ๋ฆผ, ์ฆ ์ํ๋ ๋ถ๋ถ๋ง ์ํ๋ ๊ธฐ๋ฅ์ ์ํํ ์ ์๋ค.
Stream → Collection
toList() toSet() toMap() toCollection()
- .collect( Collectors.toList() )
- .collect( Collectors.toSet() )
- .collect( Collectors.toMap(key, value) )
- .collect( Collectors.toCollection(์ปฌ๋ ์ ๊ตฌํํด๋์ค::new) )
Stream → Array
.toArray()
๐ก ๊ธฐ๋ณธํ ์คํธ๋ฆผ์ธ IntStream์ toArray()๋ง ์จ๋ ๋ฐ๋ก ๋ณํ์ด ๋๋ค.
ํ์ง๋ง ์ฐธ์กฐํ๋ค์ toArray(๋งค๊ฐ๋ณ์)๊ฐ ์์ด์ผ๋ง ๋ณํ์ด ๊ฐ๋ฅํ๋ค.
์คํธ๋ฆผ์ ํต๊ณ
counting() summingInt() ...
- ์ ์ฝ๋์์ collect()๊ฐ ์๋ ๊ฑด ์คํธ๋ฆผ์ ํต๊ณ ๋ฉ์๋๋ค์ ์ฌ์ฉํ ๊ฒ์ด๋ค.
- collect๋ฅผ ์ฌ์ฉํ๋ฉด ์ํ๋ ๋ถ๋ถ์๋ง ์ฐ์ฐ์ ์ฌ์ฉํ ์ ์๋ค.
.collect(Collectors.reducing())
: ๊ทธ๋ฃน๋ณ ๋ฆฌ๋์ฑ
- identity - ์ด๊ธฐ๊ฐ.
- BinaryOperator(acculmulator) op- ์ํํ ์ฐ์ฐ.
- BinarayOperator๋ฅผ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์
- ๋งค๊ฐ๋ณ์2๊ฐโญ ๋ฐํโญ
- ์ด ๋ ๋ณ์์ ๋ฐํ ํ์
๋ชจ๋ ๋์ผํด์ผ ํ๋ค.
- Function<T, U> mapper - T๋ฅผ U๋ก ๋ณํ ์์ ์ด ํ์ํ ๊ฒฝ์ฐ ์ฌ์ฉ.
.collect(joining(๊ตฌ๋ถ์))
: ๋ฌธ์์ด ์คํธ๋ฆผ์ ์์๋ฅผ ๋ชจ๋ ์ฐ๊ฒฐํ๋ค.
๋ฐ์ํ
'โ JAVA > โ Class & Method' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA][Stream]๊ทธ๋ฃนํ์ ๋ถํ partitioningBy() & groupingBy() (0) | 2024.12.19 |
---|---|
[JAVA][Stream]์ต์ข ์ฐ์ฐ (0) | 2024.12.17 |
[JAVA]Optional<T> (0) | 2024.12.17 |
[JAVA][Stream]์ค๊ฐ ์ฐ์ฐ-map() peek() flatMap() (1) | 2024.12.16 |
[JAVA][Stream]์ค๊ฐ ์ฐ์ฐ-filter() distinct() skip() limit() sorted() (0) | 2024.12.16 |