2013-10-01 50 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

我很高興能幫上忙。 –