Reputation: 13
I searched the answers of sorting a scala HashMap. Which is
opthash.toSeq.sortBy(_._1)
I just want to sorted by key, thus the above solution should apply.
However, here is my situation that the above solution resulted in an error:
def foo (opthash : HashMap[Int,String]) = {
val int_strin_list = opthash.toSeq.sortBy(_._1);
"return something"
}
I got the following error message:
value sortBy is not a member of Seq[(Int, String)]
Did I miss something? I am pretty sure that sortBy is a member of type Seq...
Any suggestion will be appreciated.
Upvotes: 1
Views: 1494
Reputation: 2067
Make sure to use Scala HashMap and not java HashMap. Are you sure you did not misread the error message?
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);
^
The right way to go is:
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
Or too use the mutable HashMap if that is the case.
Upvotes: 2