1

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 型のメンバーであると確信しています...

任意の提案をいただければ幸いです。

4

1 に答える 1

2

Java HashMap ではなく、必ず Scala 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 も使用してください。

于 2013-10-01T23:53:46.950 に答える