![]() |
The collect function in Scala is utilized to extract elements from a collection that satisfy a specified condition defined by a partial function. It can be invoked on any collection type, whether mutable or immutable and always returns a new collection containing the elements that meet the condition specified in the partial function. Method Signature:def collect[B](pf: PartialFunction[A, B]): Traversable[B] 1. Partial Function:The collect function takes a partial function pf as its parameter. This partial function specifies the condition that the elements of the collection must satisfy to be included in the result. It selectively extracts elements from the collection based on the logic defined within the partial function. syntax:
This syntax defines a partial function with a pattern match that specifies the input type (DataType) and the desired output type. It provides clarity and readability to the partial function definition. Detailed Syntax Example:
In this example, a partial function named extractString is created. It takes an input of type Any and returns a String. It matches any input that is of type String and returns the same string. 2. Return Type:The collect function always returns a new collection containing the elements that satisfy the condition specified in the partial function. Example:
In this example, the values in the sequence mySequence have been changed to different strings. The extractedStrings variable now holds a new sequence containing the modified string values, with each string prefixed by “Extracted: “. Examples:1. Filtering out even numbers from a list:
Output: List(2, 4, 6, 8, 10) 2. Extracting strings longer than 5 characters from a list:
Output: List(banana, orange, strawberry) 3. Converting a list of options to a list of non-empty strings:
Output: List(hello, world, scala) Conclusion: The collect function in Scala provides a convenient way to extract elements from a collection based on specific criteria. Its versatility allows it to be used with both mutable and immutable collection data structures. By utilizing a partial function, we can filter or transform elements according to our requirements, resulting in a new collection containing the desired elements. This functionality enhances the flexibility and ease of use of Scala collections, making data extraction and manipulation more straightforward across various scenarios and data types. |
Reffered: https://www.geeksforgeeks.org
Scala |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |