โšก Stream

sonjh919ยท2023๋…„ 11์›” 15์ผ
0

Java API

๋ชฉ๋ก ๋ณด๊ธฐ
16/16
post-thumbnail

๐Ÿ“Œ Stream

๐ŸŒˆ ์ด์ „์˜ ์ฒ˜๋ฆฌ ๋ฐฉ์‹

์ด์ „์—๋Š” ๋ฐฐ์—ด ๋˜๋Š” ์ปฌ๋ ‰์…˜ ์ธ์Šคํ„ด์Šค๋ฅผ ๋‹ค๋ฃฐ ๋•Œ for๋ฌธ์„ ํ™œ์šฉํ•˜์—ฌ ์š”์†Œ๋ฅผ ํ•˜๋‚˜์”ฉ ๊บผ๋‚ด์•ผ ํ–ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋กœ์ง์ด ๋ณต์žกํ•ด์งˆ์ˆ˜๋ก ์ฝ”๋“œ์˜ ์–‘์ด ๋งŽ์•„์ง€๊ณ , ๋ฃจํ”„๋ฅผ ์—ฌ๋Ÿฌ ๋ฒˆ ๋„๋Š” ๊ฒฝ์šฐ๋„ ๋ฐœ์ƒํ•˜์—ฌ ์„ฑ๋Šฅ์ด ๋–จ์–ด์ง€๋Š” ๊ฒฝ์šฐ๋„ ๋ฐœ์ƒํ•˜์˜€๋‹ค. ์ด์— ์ž๋ฐ”๋Š” 8 ๋ฒ„์ „์—์„œ Stream์ด๋ผ๋Š” api๋ฅผ ์ƒˆ๋กœ ๋‚ด๋†“์•˜๋‹ค.
Stream์€ ๊ฐ€๋…์„ฑ, ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ, ์ง€์—ฐ ํ‰๊ฐ€, ํ•จ์ˆ˜ ๊ตฌ์„ฑ ๋“ฑ ์—ฌ๋Ÿฌ ์žฅ์ ์ด ์žˆ๋‹ค.

๐ŸŒˆ Stream์˜ ์ž‘๋™ ๋ฐฉ์‹

Stream์€ ๋ฐ์ดํ„ฐ์˜ ํ๋ฆ„์ด๋‹ค. ์ปฌ๋ ‰์…˜ ์ธ์Šคํ„ด์Šค์— ํ•จ์ˆ˜ ์—ฌ๋Ÿฌ ๊ฐœ๋ฅผ ์กฐํ•ฉํ•ด์„œ ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ํ•„ํ„ฐ๋งํ•˜๊ณ  ๊ฐ€๊ณต๋œ ๊ฒฐ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค. ์ฆ‰ ๋กœ์ง์„ ํ•จ์ˆ˜ํ˜•์œผ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค. Stream์˜ ๋ฐฉ์‹์€ ํฌ๊ฒŒ 3๊ฐ€์ง€๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ๋‹ค

  1. ์ƒ์„ฑํ•˜๊ธฐ : ์ŠคํŠธ๋ฆผ ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
  2. ๊ฐ€๊ณตํ•˜๊ธฐ : ํ•„ํ„ฐ๋ง(filtering) ๋ฐ ๋งตํ•‘(mapping) ๋“ฑ ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ๋งŒ๋“ค์–ด๊ฐ€๋Š” ์ค‘๊ฐ„ ์ž‘์—…(intermediate operations)
  3. ๊ฒฐ๊ณผ ๋งŒ๋“ค๊ธฐ : ์ตœ์ข…์ ์œผ๋กœ ๊ฒฐ๊ณผ๋ฅผ ๋งŒ๋“ค์–ด๋‚ด๋Š” ์ž‘์—…(terminal operations)
  • ex)
List<Integer> numbers = new ArrayList<>();
// ์ŠคํŠธ๋ฆผ
numbers.stream()									// 1. ์ƒ์„ฑํ•˜๊ธฐ
			 .filter(i -> i > 30) 					// 2. ๊ฐ€๊ณตํ•˜๊ธฐ
			 .map(LottoNumbers::New);
			 .forEach(i -> System.out.println(i));	// 3. ๊ฒฐ๊ณผ ๋งŒ๋“ค๊ธฐ

0๊ฐœ์˜ ๋Œ“๊ธ€