[Kotlin] Collection, Sequence - 3

Chloe Choiยท2020๋…„ 12์›” 16์ผ
0

Kotlin

๋ชฉ๋ก ๋ณด๊ธฐ
4/11

Collection, Sequence - 1
Collection, Sequence - 2

๐Ÿ‘† ์ด ๊ธ€์—์„œ ์ด์–ด์ง€๋Š” ๋งˆ์ง€๋ง‰ ๊ธ€ ์ž…๋‹ˆ๋‹ค!

์ „ ๊ธ€์—์„œ Collection, Sequence์˜ ํŠน์ง• ๋ฐ ๋™์ž‘์„ ๋‹ค๋ค˜๊ณ  ์ด ๊ธ€์—์„œ๋Š” ์ด๋Ÿฐ ํŠน์ง•, ๋™์ž‘์œผ๋กœ ๊ฐ–๊ฒŒ ๋˜๋Š” Sequence์˜ ์žฅ์ ์„ ๋‹ค๋ฃฐ๊ฒŒ์šฉ

Sequence์˜ ์žฅ์ 

Keep the natural order of operations

๋ณดํ†ต ๊ตฌํ˜„ ์‹œ for๋ฌธ๊ณผ ๊ฐ™์€ ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•˜๋Š”๋ฐ Sequence์˜ ๋™์ž‘ ๋ฐฉ์‹์ด ๊ทธ ๋ฐ˜๋ณต๋ฌธ ๋™์ž‘์ˆœ์„œ(element-by-element)์™€ ์œ ์‚ฌํ•ด์„œ ๋” ์ž์—ฐ์Šค๋Ÿฝ๋‹ค๊ณ  ๋Š๋‚Œ (== Natural order)

Do a minimal number of operations

element-by-element ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰ํ•˜๋‹ค๊ฐ€ terminal ์—ฐ์‚ฐ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ฉด ์ดํ›„ ์›์†Œ์— ๋Œ€ํ•ด ์—ฐ์‚ฐ์„ ์ง„ํ–‰ํ•˜์ง€ ์•Š์Œ!

Can be infinite

Sequence๋Š” ํ•„์š”์— ์˜ํ•ด ์ž‘๋™ํ•˜๋ฏ€๋กœ ๋ฌดํ•œํ•œ ์‹œํ€€์Šค๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์Œ

+) ๋ฌดํ•œํ•œ ์‹œํ€€์Šค ๋งŒ๋“ค๊ธฐ
-> sequence generator ์‚ฌ์šฉ

  • generateSequence()
  • sequence()
generateSequence(1) {it + 1} 	// ์ฒซ๋ฒˆ์งธ์›์†Œ์™€ ๋‹ค์Œ ์›์†Œ๋ฅผ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜ ํ•„์š”
	.map {it * 2}
    .take(10) 			// ์›์†Œ๋ฅผ ์ œํ•œํ•˜๊ธฐ ์œ„ํ•ด take์™€ ๊ฐ™์€ terminal ์—ฐ์‚ฐ ํ•„์š”
    .forEach { print("$it, ") }
// Prints: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 

Do not need to create collections at every step

๋ชจ๋“  ์—ฐ์‚ฐ์— ๋Œ€ํ•ด ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•˜๋Š” Collection๊ณผ ๋‹ฌ๋ฆฌ, Sequence๋Š” ์—ฐ์‚ฐ์— ๋Œ€ํ•œ ์ฐธ์กฐ๋งŒ ์œ ์ง€!!

1-2๊ฐ€์ง€์˜ ์—ฐ์‚ฐ์„ ๊ฐ€์ง„ Collection์ด๋ผ๋ฉด ํฐ ์ฐจ์ด๋ฅผ ๊ฐ–์ง€ ์•Š์ง€๋งŒ ํฌ๊ธฐ๊ฐ€ ํฌ๊ฑฐ๋‚˜ ์—ฐ์‚ฐ์ด ๋งŽ์œผ๋ฉด intermediate collection์˜ ์ƒ์„ฑ์€ ํฐ ์˜ํ–ฅ์„ ๋ผ์น  ์ˆ˜ ์žˆ์Œ! (์˜ค๋ฒ„ํ—ค๋“œ)

Sequence๊ฐ€ ๋น„ํšจ์œจ์ ์ธ ์ผ€์ด์Šค๋Š”?

๋ชจ๋“  ๊ฒฝ์šฐ์— Sequence๊ฐ€ ๋‹ต์ธ๊ฑด ์•„๋‹˜๋ฏธ๋‹ค.

ex. sorted() ์‚ฌ์šฉ ์‹œ

  • Sequence -> List -> use sort => ์ถ”๊ฐ€์ ์ธ ์‹œ๊ฐ„ ์†Œ์š”..
  • ๋ฌดํ•œํžˆ ์ƒ์„ฑ๋˜๋Š” sequence์— ๋ฐ”๋กœ sort???? => never ending..
    • ๋ฌผ๋ก  terminal ์—ฐ์‚ฐ์„ ๋ฏธ๋ฆฌ executeํ•˜๋ฉด ๋ฌดํ•œํ•œ ์‹คํ–‰ ๋ฌธ์ œ๋Š” ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๊ฒ ์ฅฌ?

๐Ÿ˜ฌ

ํ•˜ ๋“œ๋””์–ด ์ด ์‹œ๋ฆฌ์ฆˆ๊ฐ€ ๋๋‚ฌ์Šต๋‹ˆ๋‹ค.

์ฐธ๊ณ 

https://medium.com/androiddevelopers/collections-and-sequences-in-kotlin-55db18283aca

profile
๋˜‘๋”ฑ๋˜‘๋”ฑ

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