๐Ÿ—œ๏ธ

collect(Collectors.toList()) vs toList()

์†์„ฑ
Nov 14, 2022
 

Collect(Collectors.toList()) ๋ฅผ toList()๋กœ ํ•ญ์ƒ ๋Œ€์ฒดํ•ด์„œ ์จ๋„ ๋ ๊นŒ?

 

Stream.toList()

  • JDK17 ๊ธฐ๋ฐ˜์—์„œ ์ŠคํŠธ๋ฆผ์„ ์‚ฌ์šฉํ•˜์—ฌ Collect(Collectors.toList())์„ ์‚ฌ์šฉํ•˜๋ฉด ์ด์ œ toList()๋ฅผ ์‚ฌ์šฉํ•˜๋ผ๊ณ  ๊ถŒํ•ด์ฃผ๊ณ  ์žˆ๋‹ค.
notion image
 
๐Ÿง
๋‚˜๋„ ๊ฐ€๋…์„ฑ์ด ์ข‹์•„์„œ ๋ณ€ํ˜•ํ•ด์„œ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ ์‹œํ๋ฆฌํ‹ฐ ๊ฐ•์˜ ์˜ˆ์ œ๋ฅผ ๋ณด๋ฉด์„œ ๊ณต๋ถ€ํ•˜๋˜ ์ค‘ ์ด์ƒํ•œ ์ƒํ™ฉ์ด ๋ฐœ์ƒํ–ˆ๋‹ค.
notion image
notion image
๋ญ์•ผ ์ด๊ฑฐ ์™œ์ด๋ž˜โ€ฆ
 

๋ฐœ์ƒํ•œ ์ด์œ 

  • collect(Collectors.toList()์™€ toList()๊ฐ€ ์™„์ „ํžˆ ๋˜‘๊ฐ™์€ ํ˜•ํƒœ์˜ ๊ตฌํ˜„์ฒด๋กœ ๋ฐ˜ํ™˜๋˜์ง€ ์•Š๋Š”๋‹ค.
  • collect(Collectors.toList()) ๋Š” ArrayList๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
    • There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned
  • toList()๋Š” Collectors.UnmodifiableList ๋˜๋Š” Collectors.UnmodifialbeRandomAccessList๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
[๋ช…ํ™•ํ•œ ์ฐจ์ด]
  • ์ด๋ฆ„์—์„œ ๋‚˜ํƒ€๋‚œ ๊ฒƒ์ฒ˜๋Ÿผ ์ˆ˜์ •์ด ๊ฐ€๋Šฅํ•œ ๊ตฌํ˜„์ฒด์™€ ์ˆ˜์ •์ด ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ตฌํ˜„์ฒด์— ์ฐจ์ด์ ์ด ์กด์žฌํ•œ๋‹ค.
 

ETC