2016-07-11 83 views
0

的列表,我有以下变量减少地图元组

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

我希望得到一个

List(Map -> List) 

,将看起来像下面。我们的想法是将单词B含有在其中

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

人物我已经使用了以下实现这个但是不太得到它的权利。我用下面的代码,并得到预期的结果

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)) 

不过,我想回明显的类型Map[List[(Char, Int)],List[String]]和我的情况下,返回未Any。此外,我想知道是否有更好的做整个事情本身。非常感谢!

回答

1

试试这个。

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)) 

但是,是的,我想你可能想重新考虑你的数据表示。该List[(List[(Char,Int)], String)]业务是相当繁琐。

+0

谢谢!像魅力一样工作!关于该数据表示形式,List [(List [(Char,Int)],String)]'是从不同单词的字典中计算出来的。 – borarak

+0

您可以使用以下规范: 'val words = List(“eat”,“ate”,“cheap”,“peach”,“tree”) words.map(w =>(w.toLowerCase.sorted (_._ 1).mapValues(_。map (_._ 2))' 这给出: 'Map(aet - > List(eat,ate),acehp - > List便宜,桃子),eert - >列表(树))' – Iadams