sortBy: sortBy[B](f: (A) ⇒ B)(implicit ord: math.Ordering[B]): List[A] 按照应用函数f之后产生的元素进行排序

sorted: sorted[B >: A](implicit ord: math.Ordering[B]): List[A] 按照元素自身进行排序

sortWith: sortWith(lt: (A, A) ⇒ Boolean): List[A] 使用自定义的比较函数进行排序,比较函数boolean

用法

<code class="hljs coffeescript has-numbering">val nums = List(<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>)
val sorted = nums.sorted <span class="hljs-regexp">//</span>List(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>) val users = List((<span class="hljs-string">"HomeWay"</span>,<span class="hljs-number">25</span>),(<span class="hljs-string">"XSDYM"</span>,<span class="hljs-number">23</span>))
val sortedByAge = users.sortBy{<span class="hljs-reserved">case</span><span class="hljs-function"><span class="hljs-params">(user,age)</span> =></span> age} <span class="hljs-regexp">//</span>List((<span class="hljs-string">"XSDYM"</span>,<span class="hljs-number">23</span>),(<span class="hljs-string">"HomeWay"</span>,<span class="hljs-number">25</span>))
val sortedWith = users.sortWith{<span class="hljs-reserved">case</span><span class="hljs-function"><span class="hljs-params">(user1,user2)</span> =></span> user1._2 < user2._2} <span class="hljs-regexp">//</span>List((<span class="hljs-string">"XSDYM"</span>,<span class="hljs-number">23</span>),(<span class="hljs-string">"HomeWay"</span>,<span class="hljs-number">25</span>))</code>

How to sort a Scala Map by key or value (sortBy, sortWith)

By Alvin Alexander. Last updated: Jun 6, 2015

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.23, “How to Sort an Existing Map by Key or Value”

Problem

You have an unsorted map and want to sort the elements in the map by the key or value.

Solution

Given a basic, immutable Map:

scala> val grades = Map("Kim" -> 90,
| "Al" -> 85,
| "Melissa" -> 95,
| "Emily" -> 91,
| "Hannah" -> 92
| )
grades: scala.collection.immutable.Map[String,Int] = Map(Hannah -> 92, Melissa -> 95, Kim -> 90, Emily -> 91, Al -> 85)

You can sort the map by key, from low to high, using sortBy:

scala> import scala.collection.immutable.ListMap
import scala.collection.immutable.ListMap scala> ListMap(grades.toSeq.sortBy(_._1):_*)
res0: scala.collection.immutable.ListMap[String,Int] = Map(Al -> 85, Emily -> 91, Hannah -> 92, Kim -> 90, Melissa -> 95)

You can also sort the keys in ascending or descending order using sortWith:

// low to high
scala> ListMap(grades.toSeq.sortWith(_._1 < _._1):_*)
res0: scala.collection.immutable.ListMap[String,Int] = Map(Al -> 85, Emily -> 91, Hannah -> 92, Kim -> 90, Melissa -> 95) // high to low
scala> ListMap(grades.toSeq.sortWith(_._1 > _._1):_*)
res1: scala.collection.immutable.ListMap[String,Int] = Map(Melissa -> 95, Kim -> 90, Hannah -> 92, Emily -> 91, Al -> 85)

You can sort the map by value using sortBy:

scala> ListMap(grades.toSeq.sortBy(_._2):_*)
res0: scala.collection.immutable.ListMap[String,Int] = Map(Al -> 85, Kim -> 90, Emily -> 91, Hannah -> 92, Melissa -> 95)

You can also sort by value in ascending or descending order using sortWith:

// low to high
scala> ListMap(grades.toSeq.sortWith(_._2 < _._2):_*)
res0: scala.collection.immutable.ListMap[String,Int] = Map(Al -> 85, Kim -> 90, Emily -> 91, Hannah -> 92, Melissa -> 95) // high to low
scala> ListMap(grades.toSeq.sortWith(_._2 > _._2):_*)
res1: scala.collection.immutable.ListMap[String,Int] = Map(Melissa -> 95, Hannah -> 92, Emily -> 91, Kim -> 90, Al -> 85)

In all of these examples, you’re not sorting the existing map; the sort methods result in a new sorted map, so the output of the result needs to be assigned to a new variable.

Also, you can use either a ListMap or a LinkedHashMap in these recipes. This example shows how to use a LinkedHashMap and assign the result to a new variable:

scala> val x = collection.mutable.LinkedHashMap(grades.toSeq.sortBy(_._1):_*)
x: scala.collection.mutable.LinkedHashMap[String,Int] =
Map(Al -> 85, Emily -> 91, Hannah -> 92, Kim -> 90, Melissa -> 95) scala> x.foreach(println)
(Al,85)
(Emily,91)
(Hannah,92)
(Kim,90)
(Melissa,95) 转:https://blog.csdn.net/mengxing87/article/details/51636080 有关 sortWith 底层,请看这里:https://www.cnblogs.com/nucdy/p/9270594.html
												

scala sortBy and sortWith的更多相关文章

  1. Scala里面的排序函数的使用

    排序方法在实际的应用场景中非常常见,Scala里面有三种排序方法,分别是: sorted,sortBy ,sortWith 分别介绍下他们的功能: (1)sorted 对一个集合进行自然排序,通过传递 ...

  2. Scala数据结构(二)

    一.集合的基础操作 1,head头信息 //获取集合的第一个元素 val list = List(,,) list.head // 2,tail尾信息 //获取集合除去头元素之外的所有元素 val l ...

  3. Scala List的排序函数sortWith

    //原始方法: //val list=List("abc","bcd","cde") scala> list.sortWith( (s ...

  4. [Ramda] Sort, SortBy, SortWith in Ramda

    The difference between sort, sortBy, sortWith is that: 1. sort: take function as args. 2. sortBy: ta ...

  5. Scala中sortBy和Spark中sortBy区别

    Scala中sortBy是以方法的形式存在的,并且是作用在Array或List集合排序上,并且这个sortBy默认只能升序,除非实现隐式转换或调用reverse方法才能实现降序,Spark中sortB ...

  6. Scala比较器:Ordered与Ordering

    在项目中,我们常常会遇到排序(或比较)需求,比如:对一个Person类 case class Person(name: String, age: Int) { override def toStrin ...

  7. Scala HandBook

    目录[-] 1.   Scala有多cool 1.1.     速度! 1.2.     易用的数据结构 1.3.     OOP+FP 1.4.     动态+静态 1.5.     DSL 1.6 ...

  8. 快学scala

    scala 1.   scala的由来 scala是一门多范式的编程语言,一种类似java的编程语言[2] ,设计初衷是要集成面向对象编程和函数式编程的各种特性. java和c++的进化速度已经大不如 ...

  9. Scala 运算符和集合转换操作示例

    Scala是数据挖掘算法领域最有力的编程语言之一,语言本身是面向函数,这也符合了数据挖掘算法的常用场景:在原始数据集上应用一系列的变换,语言本身也对集合操作提供了众多强大的函数,本文将以List类型为 ...

随机推荐

  1. poj 1679 判断MST是不是唯一的 (次小生成树)

    判断MST是不是唯一的 如果是唯一的 就输出最小的权值和 如果不是唯一的 就输出Not Unique! 次小生成树就是第二小生成树  如果次小生成树的权值和MST相等  那么MST就不是唯一的 法一: ...

  2. 用SQL统计每分钟的访问量

    以前面试没有理解到它什么意思的一道题,回忆中是这个题意 ), to_char(r.datelastmaint, 'yyyy-mm-dd hh24:mi'), sum(abs(r.tranamt)) f ...

  3. mysql数据库备份 mysqldump

    一.--all-databases /application/mysql3307/bin/mysqldump -uroot -S /application/mysql3307/logs/mysql.s ...

  4. springmvc传参问题

    @RequestMapping(value = "/addHit", method = { RequestMethod.POST, RequestMethod.GET }) pub ...

  5. 域名解析到Nginx服务器项目上

    第一步:先将域名解析到 IP 上 解析完后,如下 第二步:Nginx服务器配置servername 修改 /usr/local/nginx/conf/nginx.conf (你的配置文件可能不在这个目 ...

  6. php字符串截取

    保留字符串前面的 substr($str,start[,$length]); start  为负数 则从后面开始截取 leng为负数则返回的字符串将从 $str 结尾处向前数第 start 个字符开始 ...

  7. 使用boost线程定时器作为后台线程来切换主循环程序状态方法2

    上一篇的方法主要使用的是:通过线程延时实 现的定时,并且只能定时一次,如果需要对此定时处理,就需要使用下面的定时器: #include "stdafx.h" #include &l ...

  8. BZOJ.4903.[CTSC2017]吉夫特(Lucas DP)

    题目链接 首先\(C(n,m)\)为奇数当且仅当\(n\&m=m\). 简要证明: 因为是\(mod\ 2\),考虑Lucas定理. 在\(mod\ 2\)的情况下\(C(n,m)\)最后只会 ...

  9. java的关键字与保留字

    1,Java 关键字列表 (依字母排序 共50组): abstract, assert, boolean, break, byte, case, catch, char, class, const(保 ...

  10. Saltstack 命令

    命令格式 salt '<操作目标>' <方法>[参数] 查看被控主机内存使用情况 [root@node1 ~]# salt '*' cmd.run 'free -h' node ...