2013-10-01 48 views
1

我搜索了对一个scala HashMap进行排序的答案。 这是对一个键入的Scala HashMap排序

opthash.toSeq.sortBy(_._1) 

我只是想通过键排序,因此,上述解决方案应该适用。

然而,这里是我的情况是,上述方案导致错误:

def foo (opthash : HashMap[Int,String]) = { 
    val int_strin_list = opthash.toSeq.sortBy(_._1); 
    "return something" 
} 

,我得到了以下错误消息:

value sortBy is not a member of Seq[(Int, String)] 

我错过了什么?我很确定sortBy是Seq类型的成员...

任何建议将不胜感激。

+1

我可以在2.10上完美编译您的方法您使用的是什么版本的scala?看起来甚至2.8(即2003年)有seq的sortBy。 –

+1

和[在线演示,显示这真的起作用](http://www.scalakata.com/524b53dfebb25c7f5d828755)(点击绿色按钮运行) –

+0

编译器反对使用分号和下划线的变量名称... –

回答

2

确保使用Scala HashMap而不是Java HashMap。你确定你没有误读错误信息吗?

scala> import java.util.HashMap 
import java.util.HashMap 

scala> def foo (opthash : HashMap[Int,String]) = { 
    |  val int_strin_list = opthash.toSeq.sortBy(_._1); 
    |  "return something" 
    | } 
<console>:13: error: value toSeq is not a member of java.util.HashMap[Int,String] 
      val int_strin_list = opthash.toSeq.sortBy(_._1); 
             ^

正确的方法走的是:

scala> import scala.collection.immutable.HashMap 
import scala.collection.immutable.HashMap 

scala> def foo (opthash : HashMap[Int,String]) = { 
    |  val int_strin_list = opthash.toSeq.sortBy(_._1); 
    |  "return something" 
    | } 
foo: (opthash: scala.collection.immutable.HashMap[Int,String])String 

还是太使用可变HashMap的,如果是这样的话。

+0

谢谢。我正在使用Scala 2.7。确保使用scala的HashMap并使用最新的scala之后,问题就解决了! –

+0

我很高兴能帮上忙。 –