http://www.aboutyun.com/thread-22942-1-1.html
scala,因为平时写的少,遇到问题,就调出命令行工具,实际验证操作一次
_*代表变参数 可传入多个参数值,seq,list类型的参数
ListMap(grades.toSeq.sortBy(
_
.
_
2
)
:_
*)
ListMap(x
:
_
*)
进入 /atmd/gmd/chline/scala/bin目录,进入scala的命令行练习
[gmd@tcbj3-dmetl01 bin]$ ./scala
Welcome to Scala 2.11.12 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).
Type in expressions for evaluation. Or try :help.
scala> val a=Map("kim"->30,"tom"->20)
a: scala.collection.immutable.Map[String,Int] = Map(kim -> 30, tom -> 20)
scala> import scala.collection.immutable.ListMap
import scala.collection.immutable.ListMap
//这里为什么要转换成seq类型,因为map类型没有sortBy排序函数,是为了用而转类型
scala> ListMap(a.toSeq.sortBy(_._2):_*)
res0: scala.collection.immutable.ListMap[String,Int] = Map(tom -> 20, kim -> 30)
scala> a.toSeq
res3: Seq[(String, Int)] = ArrayBuffer((kim,30), (tom,20))
//降序就在前面加减号
scala> res3.sortBy(-_._2)
res5: Seq[(String, Int)] = ArrayBuffer((kim,30), (tom,20))
scala> res3.sortBy(_._2)
res6: Seq[(String, Int)] = ArrayBuffer((tom,20), (kim,30))
scala> ListMap(a.toSeq.sortBy(_._2):_*)
res7: scala.collection.immutable.ListMap[String,Int] = Map(tom -> 20, kim -> 30)
//另一种排序方法sortWith 升序
scala> ListMap(a.toSeq.sortWith(_._2<_._2):_*)
res9: scala.collection.immutable.ListMap[String,Int] = Map(tom -> 20, kim -> 30)
//
scala> val x=collection.mutable.LinkedHashMap(a.toSeq.sortBy(_._2):_*)
x: scala.collection.mutable.LinkedHashMap[String,Int] = Map(tom -> 20, kim -> 30)
scala> x.foreach(println)
(tom,20)
(kim,30)
scala> val x2=a.toSeq.sortBy(_._2)
x2: Seq[(String, Int)] = ArrayBuffer((tom,20), (kim,30))
scala> ListMap(x2:_*)
res11: scala.collection.immutable.ListMap[String,Int] = Map(tom -> 20, kim -> 30)
scala> ListMap(x2)
<console>:14: error: type mismatch;
found : Seq[(String, Int)]
required: (?, ?)
ListMap(x2)
^
scala> def printAll(strings:String*){strings.foreach(println)}
printAll: (strings: String*)Unit
scala> val fruits=List("apple","banana")
fruits: List[String] = List(apple, banana)
scala> printAll(fruits)
<console>:15: error: type mismatch;
found : List[String]
required: String
printAll(fruits)
^
scala> printAll(fruits:_*)
apple
banana