GroupBy

GroupBy is used to partition specific collections into a map of other Traversable collections according to a specific partitioning function. It can be defined formally as follows:

def groupBy[K](f: ((A, B)) ⇒ K): Map[K, Map[A, B]]  

Let's see an example as follows:

scala> // Given a list of numbers
scala> // Group them as positive and negative numbers.
scala> List(1,-2,3,-4) groupBy (x => if (x >= 0) "positive" else "negative")
res6: scala.collection.immutable.Map[String,List[Int]] = Map(negative -> List(-2, -4), positive -> List(1, 3))

In Scala, if you want to select all the elements in a Traversable collection but the last one, you can use init. In the next subsection, we will see examples of it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.175.101