scala ----ListMap(mx.toSeq.sortBy(_._1):_*)

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值