Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GroupBy in scala

Tags:

scala

I have

val a = List((1,2), (1,3), (3,4), (3,5), (4,5))

I am using A.groupBy(_._1) which is groupBy with the first element. But, it gives me output as

Map(1 -> List((1,2) , (1,3)) , 3 -> List((3,4), (3,5)), 4 -> List((4,5)))

But, I want answer as

Map(1 -> List(2, 3), 3 -> List(4,5) , 4 -> List(5))

So, how can I do this?

like image 815
user2663411 Avatar asked Nov 02 '15 07:11

user2663411


People also ask

What is groupBy in Scala?

Scala groupBy is used for grouping of elements based on some criteria defined as a predicate inside the function. This function internally converts the collection into map object and this map object work on key value pair. This is basically used for storing and retrieving of the elements.

What is groupBy in Spark?

The GROUP BY clause is used to group the rows based on a set of specified grouping expressions and compute aggregations on the group of rows based on one or more specified aggregate functions.

Does groupBy preserve order Scala?

groupBy as defined on TraversableLike produces an immutable. Map , so you can't make this method produce something else. The order of the elements in each entry is already preserved, but not the order of the keys. The keys are the result of the function supplied, so they don't really have an order.


1 Answers

You can do that by following up with mapValues (and a map over each value to extract the second element):

scala> a.groupBy(_._1).mapValues(_.map(_._2))
res2: scala.collection.immutable.Map[Int,List[Int]] = Map(4 -> List(5), 1 -> List(2, 3), 3 -> List(4, 5))
like image 124
Shadowlands Avatar answered Oct 15 '22 04:10

Shadowlands