Collect(Collectors.toList()) 를 toList()로 항상 대체해서 써도 될까?
Stream.toList()
- JDK17 기반에서 스트림을 사용하여
Collect(Collectors.toList())
을 사용하면 이제toList()
를 사용하라고 권해주고 있다.

나도 가독성이 좋아서 변형해서 사용했는데 시큐리티 강의 예제를 보면서 공부하던 중 이상한 상황이 발생했다.


뭐야 이거 왜이래…
발생한 이유
- 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를 반환한다.
[명확한 차이]
- 이름에서 나타난 것처럼 수정이 가능한 구현체와 수정이 불가능한 구현체에 차이점이 존재한다.