Good Place. Good Things. Good Time.

Scala collect

Scala collect

Introduction to Scala collect.

Collect function is used to collect elements from the given collection. Collect function can be used with the collection data structure to pick up some elements which satisfy the given condition. Collect function can be used with the mutable and immutable collection data structure in scala. It always returns us the new collection containing all the elements that satisfy the condition; this condition is referred to as the Partial function. That means it took the partial function and applied it to the all the values present inside the given collection.

Syntax:

We know that it is a function available in Scala, which takes up the partial function as the parameter and will be applied on all the variables present inside it and return us the elements that satisfy the condition.

Let’s see the syntax of this function.

This is the syntax as per the scala doc:

def collect[B](pf: PartialFunction[A, B]): Traversable[B]
mylistName.collect(Your_partial_function)

As you can see in the above lines of code, we can call this function on our collection object by specifying a partial function inside it as the parameter. So after calculating the values, it will return us a new collection with result values inside it.

How does collect Function Work in Scala?

We know that the collect function in scala to collect the element from a collection that are of the same type. We can call this function on any collection type, whether it is mutable or immutable. It will always return us the new collection as a result of the given collection element.

Method signature:

def collect[B](pf: PartialFunction[A, B]): Traversable[B] (This is as per the scala documentation)

1. Partial Function

The collect function takes a partial function as the parameter. This partial function will be responsible for performing the operation on the each element of the collection. It will pick out all the elements from the given collection that will satisfies the partial function.

Syntax:

case var_name: Data_type => var_name

In the above lines of code, we can define a partial function, what it will take and what it is going to return. This is simple to use and readable also.

Below find the more detailed syntax for its usage in scala:

val demo: PartialFunction[String, String] = {
case "some string" => "return string"
}

In the above lines of code, we are creating one partial function which will take up the string parameter and return us the string. In this way, we can specify our type what we want from the given collection.

2. Return Type

Collect function will always return us the new collection, which will contain all the elements from the given collection data structure.

Example:

object Main extends App{
val mysequence: Seq[Any] = Seq("hello", "hello again", 40, "bye", 60, 80, 100, "i am strinf as well !!")
val result: Seq[String] = mysequence.collect{ case mystr: String => mystr }
}

It is just a simple program in which we are creating a sequence of ‘any’ type in scala; also, we are specifying the different type of element inside it, for instance, string and integer. But we want to extract only the string elements from the collection, so we call the collect method and pass our partial function to match only the string. In this way, we can use a collect function in scala.

Points to be remembered while using a collect function in scala:

  • This can be used with the mutable and immutable collection data structure.
  • This function takes a partial function as the argument; this function will calculate and pick up the elements which satisfies the given condition. Always it will return as a result in the form of a new collection contain all the element.

Examples of Scala collect.

Given below are the examples of Scala collect:

Example #1

In this example, we are creating a sequence collection of any type. Using the collect function, we are trying to extract the integer, string, and double values from the given collection data structure in the scala.

Code:

object Main extends App{
// Your code here!
println("Demo to understand collect function in scala !!")
println("Extrat only string values ::")
val mysequence1: Seq[Any] = Seq("hello", "hello again", 40, "bye", 60, 80, 100, "i am string as well !!")
val result1: Seq[String] = mysequence1.collect{ case mystr: String => mystr }
println("Result is ::")
println(result1)
println("***********************************************************************")
println("Extrat only integer values ::")
val mysequence2: Seq[Any] = Seq("Amit", 200, 20.1, "sumit", 300, 30.2, "Geet", 400 , 40.1, "vinit", 500, 50.1)
val result2: Seq[Integer] = mysequence2.collect{ case myrollno: Integer => myrollno }
println("Result is ::")
println(result2)
println("***********************************************************************")
println("Extrat only double values ::")
val mysequence3: Seq[Any] = Seq("Amit", 200, 20.1, "sumit", 300, 30.2, "Geet", 400 , 40.1, "vinit", 500, 50.1)
val result3: Seq[Double] = mysequence3.collect{ case myrollno: Double => myrollno }
println("Result is ::")
println(result3)
}

Output:

Scala collect 1

Example #2

In this example, we are trying to fetch the float value from the collect data structure. Here also we are using the collect function to extract the element from the collection. Also, we are not using any library; this is an in build function available in scala.

Code:

object Main extends App{
// Your code here!
println("Demo to understand collect function in scala !!")
println("Extrat only float values ::")
val mysequence1: Seq[Any] = Seq(2.1f, "test 1", "test2", 5.7f, "test 3", "test 4", "tets 5", 8890, 1.0f, 8.9f, 2.4f)
val result1: Seq[Float] = mysequence1.collect{ case mystr: Float => mystr }
println("Result is ::")
println(result1)
println("***********************************************************************")
}

Output:

Scala collect 2

Conclusion

By using the collect function, we can easily extract the data from the collection, which are of the same type. Also, we can use this function with any mutable and immutable collection data structure, which makes it more easy and more handy to use.

Recommended Articles

This is a guide to Scala collect. Here we discuss the introduction; how does collect function work in scala? And examples, respectively. You may also have a look at the following articles to learn more –

  1. Scala Date Function
  2. Scala Byte
  3. Scala zipwithindex
  4. Scala Object

The post Scala collect appeared first on EDUCBA.

Read original article here: Scala collect

Read original article here: Scala collect



Disclaimers and Denial of responsibility..!

Denial of responsibility! TheTopMag.com is an automatic aggregator of all media around the world. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – jamesonline999@gmail.com . The content will be deleted within 72 hours.
You might also like
Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.