Reduce a List of Map of Tuples

时间:2016-07-11 22:03:17

标签: scala scala-collections

I have the following variable

val x1 =  List((List(('a',1), ('e',1), ('t',1)),"eat"), (List(('a',1), ('e',1), ('t',1)),"ate"))

I want to get a

List(Map -> List)

that will look something like the following. The idea is to group words b the characters contained in them

Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))

I have used the following to achieve this however not quite getting it right. I have used the following code and get the expected result

scala> val z1 = x1.groupBy(x => x._1 )
                  .map(x => Map(x._1 -> x._2.map(z=>z._2)))
                  .fold(){(a,b) => b}
z1: Any = Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))

However, I would like to return the obvious type Map[List[(Char, Int)],List[String]] and not Any as is returned in my case. Also, i'm wondering if there is a better of doing the whole thing itself. Many thanks!

1 个答案:

答案 0 :(得分:1)

Try this.

scala> x1.groupBy(_._1).mapValues(_.map(_._2))
res2: scala.collection.immutable.Map[List[(Char, Int)],List[String]] = Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))

But, yeah, I think you might want to reconsider your data representation. That List[(List[(Char,Int)], String)] business is rather cumbersome.