How to collate list items with the same first item onto a map

list, scala

Solution

I'm not sure what the types in your data structure are, but maybe you can adapt this. This assumes you have a collection of tuples:

val items = 
  List((1, "a", 30),
       (1, "b", 20),
       (1, "c", 22),
       (2, "a", 32),
       (2, "c", 10))

items
  .groupBy{ case (a,b,c) => a }
  .mapValues(_.map{ case (a,b,c) => (b,c) })

// Map(1 -> List((a,30), (b,20), (c,22)), 2 -> List((a,32), (c,10)))

Or, more succinctly:

items.groupBy(_._1).mapValues(_.map(t => (t._2, t._3)))

The `collect` method is something else entirely (basically, it's `map` that drops non-matching values). The `groupBy` method is what you were really looking for.

Problem

I know this is probably a very simple List operation in Scala, but I'm a newbie and can't figure it out. I have a query that returns a result set with a series of values, grouped by a common id. For example: Result Set: ``` [{ 1, "a", 30 }, { 1, "b", 20 }, { 1, "c", 22 }, { 2, "a", 32 }, { 2, "c", 10 }] ``` and what I'd like to do is put this into a map as such: ``` 1 -> [{"a", 30}, {"b", 20}, {"c", 22}] 2 -> [{"a", 32}, {"c", 10}] ``` I think the collect method can be used for this but can't figure it out.

Original source