Junior — Middle
How do methods of transforming data streams into lists differ in various cases of using Streams API?
sobes.tech AI
Answer from AI
In Java Streams API, transforming a data stream into a list is usually done using the terminal operation collect(Collectors.toList()). However, depending on the context and requirements, different methods may be used:
- Collecting into a list with
Collectors.toList()— returns a list but does not guarantee a specific list type or immutability.
List<String> list = stream.collect(Collectors.toList());
- Collecting into a specific list type with
Collectors.toCollection()— allows specifying a particular list implementation, such asLinkedList:
List<String> linkedList = stream.collect(Collectors.toCollection(LinkedList::new));
- Using
toArray()with subsequent conversion — if an array is needed first, then a list:
List<String> list = Arrays.asList(stream.toArray(String[]::new));
- Using
forEach()to add elements to an existing list — less functional and not recommended, as it breaks immutability and stream processing.
The choice of method depends on the requirements for list type, mutability, and performance.