Which method is used to collect the results of a stream operation into a List?
Answer:
Explanation:
The collect()
method is used to collect the results of a stream operation into a List
, Set
, or other collection types. It is one of the most commonly used terminal operations in the Stream API, as it allows developers to gather the processed elements of a stream into a single collection that can be used later in the program. The collect()
method is highly flexible and can be customized using various collectors provided by the Collectors
utility class.
For example, you can use Collectors.toList()
to collect the elements into a List
, Collectors.toSet()
to collect them into a Set
, or Collectors.joining()
to concatenate them into a single string. This flexibility makes the collect()
method an essential tool for converting streams back into collections after performing various operations like filtering, mapping, and reducing.
Collecting the results of a stream operation is often the final step in a stream pipeline. Once the collect()
method is invoked, the stream is consumed, and the resulting collection is returned. This collection can then be used for further processing or output. The collect()
method is particularly powerful in scenarios where you need to aggregate or organize the data into a specific structure.