Junior — Middle
Mis on meetodi collect funktsioon Stream API-s ja millistel juhtudel on soovitatav seda kasutada?
sobes.tech AI
Vastus AI-lt
The collect method in the Stream API is used to transform the elements of a stream into another form, most often into a collection such as a list, set, or map. It accepts an object of type Collector, which defines how to aggregate the elements.
It is recommended to use collect when you need to gather the results of stream processing into a final data structure for further use. For example, collecting filtered elements into a list:
List<String> filtered = stream.filter(s -> s.startsWith("A"))
.collect(Collectors.toList());
Thus, collect is a terminal operation that aggregates stream elements into the required container or computes the final value.