clwn.net
当前位置:首页 >> sCAlA 集合 >>

sCAlA 集合

scala> val l = List(5,4,3,6,2,1)l: List[Int] = List(5, 4, 3, 6, 2, 1)scala> l.sortedres2: List[Int] = List(1, 2, 3, 4, 5, 6)scala> l.sorted(Ordering.Int.reverse)res3: List[Int] = List(6, 5, 4, 3, 2, 1)如果你需要特定的排序算法,那么请使用sortWith方法scala> l.sortWith((a,b)=>a>b)res4: List[Int] = List(6, 5, 4, 3, 2, 1)

这两天碰到3个一样的问题,所以我直接用之前回答的答案.可以用sorted的方法scala> val list = List(3,2,6,1,7,5,2)list: List[Int] = List(3, 2, 6, 1, 7, 5, 2)scala> list.sortedres0: List[Int] = List(1, 2, 2, 3, 5, 6, 7)scala> val m = Map(-5->2,1->5,6->4,2->8,9->

如何对Map中的Key或Value进行排序 其实很简单代码如下:// sort by key can use sorted m.toList.sorted foreach { case (key,value) => println(key + " = " + value) }-2 = 5-1 = -40 = -161 = 22 = 65 = 9// sort by value m.toList sortBy ( _._2 ) foreach { case (key,value) => println(key + " = " + value) }0 = -16-1 = -41 = 2-2 = 52 = 65 = 9

scala>vall=List(5,4,3,6,2,1)l:List[Int]=List(5,4,3,6,2,1)scala>l.sortedres2:List[Int]=List(1,2,3,4,5,6)scala>l.sorted(Ordering.Int.reverse)res3:List[Int]=List(6,5,4,3,2,1)如果你需要特定的排序

如何对Map中的Key或Value进行排序其实很简单代码如下:// sort by key can use sortedm.toList.sorted foreach {case (key,value) =>println(key + " = " + value)}-2 = 5-1 = -40 = -161 = 22 = 65 = 9// sort by valuem.toList sortBy ( _._2 ) foreach {case (key,value) =>println(key + " = " + value)}0 = -16-1 = -41 = 2-2 = 52 = 65 = 9

val list1 = List(1, 2, 3, 4, 5, 6)list1.sortedlist1.sortWith(_ > _)val sortedSet = scala.collection.immutable.SortedSet(2, 3, 4, 5, 1)

vallist1=List(1,2,3,4,5,6)list1.sortedlist1.sortWith(_>_)valsortedSet=scala.collection.immutable.SortedSet(2,3,4,5,1)

val list1 = List(1, 2, 3, 4, 5, 6) list1.sorted list1.sortWith(_ > _) val sortedSet = scala.collection.immutable.SortedSet(2, 3, 4, 5, 1)

val list1 = List(1, 2, 3, 4, 5, 6)list1.sortedlist1.sortWith(_ > _)val sortedSet = scala.collection.immutable.SortedSet(2, 3, 4, 5, 1)

在List对象上直接调用sorted方法即可,例如:val nums = List(1,3,2,4)val sorted = nums.sorted //调用完后sorted为List(1,2,3,4)如果List中的元素是复合对象,那可以用sortBy指定要按复合对象中的哪个成员变量来排序,例如:val users = List(("

网站首页 | 网站地图
All rights reserved Powered by www.clwn.net
copyright ©right 2010-2021。
内容来自网络,如有侵犯请联系客服。zhit325@qq.com