Junior — Middle
If I call the toList() method on a Stream, will the result be an ArrayList or another collection type?
sobes.tech AI
Answer from AI
The toList() method in the Stream interface (starting from Java 16) returns an unmodifiable list, but the specific collection type is not guaranteed and is not necessarily an ArrayList. Unlike collect(Collectors.toList()), which usually returns an ArrayList, Stream.toList() may return a different type of list optimized for the specific implementation.
Example:
List<String> list = Stream.of("a", "b", "c").toList();
// list is unmodifiable, attempting to modify it will throw UnsupportedOperationException
Therefore, you cannot rely on the result being exactly an ArrayList. If you specifically need an ArrayList, it is better to use collect(Collectors.toList()).