scala的sorted,sortBy,sortWith

val lst = List(1,3,2,4,5)
    //scala中对于集合的排序有三种方法:sorted,sortBy,sortWith
    //sorted方法对一个集合进行天然排序,传递一个Ordering隐式参数 def sorted[B >: A](implicit ord: Ordering[B]): Repr
    val nl = lst.sorted  //1 2 3 4 5
    for(i <- nl)
      {
        println(i)
      }
    //def sortBy[B](f: A => B)(implicit ord: Ordering[B]): Repr = sorted(ord on f)  //ord中有一个on方法,接收一个函数参数f
    println(lst.sortBy(a=>a).reverse) //5 4 3 2 1

    //def sortWith(lt: (A, A) => Boolean): Repr = sorted(Ordering fromLessThan lt)
    print(lst.sortWith(_<_)) //  1 2  3 4  5
相关文章
相关标签/搜索