0

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!

borarak
  • 1,130
  • 1
  • 13
  • 24

1 Answers1

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.

jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Thanks! Worked like a charm! About that data representation, `List[(List[(Char,Int)], String)]` is computed from a dictionary of different words. – borarak Jul 11 '16 at 22:39
  • You could use the following canonicalisation: `val words = List("eat", "ate", "cheap", "peach", "tree") words.map(w => (w.toLowerCase.sorted, w)).groupBy(_._1).mapValues(_.map (_._2))` This gives: `Map(aet -> List(eat, ate), acehp -> List(cheap, peach), eert -> List(tree))` – Iadams Jul 12 '16 at 11:22