HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🛁
공부기록
/
🗜️
collect(Collectors.toList()) vs toList()
🗜️

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

속성
Nov 14, 2022
Collect(Collectors.toList()) 를 toList()로 항상 대체해서 써도 될까?Stream.toList()발생한 이유ETC
 

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

Stream.toList로 Stream.collect(toList())를 대체해도 되는 걸까?
최근 JDK 17 release 되었고, JDK 11 다음의 LTS 버전으로서 오랫동안 지원이 되는 만큼 업무/개인프로젝트 등에서 적극적으로 사용하고 있다. Stream.toList() JDK17 기반에서 Stream을 사용해 List로 변환(collect)하다보면 IntelliJ에서 자주 보는 메세지가 있다. 위의 경우인데, collect(toList()) 대신 Stream.toList() 를 사용할 수 있다는 정보성 메시지이다. 그래서 나는 보통 JDK 17로 개발을 할 때, 아래와 같이 사용했다.
Stream.toList로 Stream.collect(toList())를 대체해도 되는 걸까?
https://binux.tistory.com/146
Stream.toList로 Stream.collect(toList())를 대체해도 되는 걸까?
Stream을 List로 변환하는 다양한 방법과 차이(Collectors.toList() vs Stream.toList())
java17 을 사용하고 sonarlint 로 체크를 해보니 "Stream.toList()" method should be used instead of "collectors" when unmodifiable list needed 로 collect(Collectors.toList())를 Stream.toList() 로 변경하는 것을 권고 했다. 왜 그런 것일까? java8에서 .collect(Collectors.toList()) 를 사용할 수 있는데, 문제는 리턴되는 List가 수정이 가능하기 때문에 java10 에서 수정불가능한(unmodifiable) List 로 반환되도록 toUnmodifiableList() 가 새롭게 등장했다고 한다.
Stream을 List로 변환하는 다양한 방법과 차이(Collectors.toList() vs Stream.toList())
https://velog.io/@cieroyou/Stream%EC%9D%84-List%EB%A1%9C-%EB%B3%80%ED%99%98%ED%95%98%EB%8A%94-%EB%8B%A4%EC%96%91%ED%95%9C-%EB%B0%A9%EB%B2%95%EA%B3%BC-%EC%B0%A8%EC%9D%B4Collectors.toList-vs-Stream.toList
Stream을 List로 변환하는 다양한 방법과 차이(Collectors.toList() vs Stream.toList())