Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not understanding groupBy method

Tags:

scala

groupBy is defined as : def groupBy[K](f: A => K): immutable.Map[K, Repr] = {

So f is a function which takes an A and returns K , K is the current type so in below example is List ?

Using below :

  val l : List[(String , String)] = List( ("a" , "line1") , ("b" , "line2") , ("b" , "line3") , ("a" , "line4"))
  val gm : Map[String,List[(String, String)]] = l.groupBy(_._1)

I'm attempting to convert to type :

  val m : Map[String , List[String]] = Map("a" -> List("line1" , "line4") , "b" -> List("line2" , "line3"))

But instead I receive type : Map[String,List[(String, String)]]

How to amend groupBy(_._1) to return excepted type ? Why is _._1 a function of type A => K ?

like image 690
blue-sky Avatar asked Feb 09 '26 19:02

blue-sky


1 Answers

It might be a bit easier to follow if we will introduce type aliases:

scala> type Key = String
defined type alias Key

scala> type Value = String
defined type alias Value

scala> val l: List[(Key, Value)] = List("a" -> "line1", "b" -> "line2", "b" -> "line3", "a" -> "line4")
// l: List[(Key, Value)] = List((a,line1), (b,line2), (b,line3), (a,line4))

scala> l.groupBy(_._1)
// res0: scala.collection.immutable.Map[Key,List[(Key, Value)]] = Map(b -> List((b,line2), (b,line3)), a -> List((a,line1), (a,line4)))

Now it's evident that groupBy takes Key out of (Key, Value) pairs, but lefts pairs intact, just aggregates them together basing on Key. What we need to do is to select values out of this grouped pairs:

scala> res0.mapValues(group => group.map(kv => kv._2))
// res2: scala.collection.immutable.Map[Key,List[Value]] = Map(b -> List(line2, line3), a -> List(line1, line4))
like image 113
om-nom-nom Avatar answered Feb 13 '26 14:02

om-nom-nom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!