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. mysql中delete from in子查询删除失败

    遇到一个情况,想通过表1的id找到表2,删除表2中barcode关联的库存数据,然后一直不能失败,如下: delete from 库存表 where BARCODE in( select BARCOD ...

  2. 注册表键值明明存在OpenSubKey始终返回null,解决方案

    先上代码及实例 RegistryKey rsg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Macromedia\FlashPaper Pri ...

  3. 【AtCoder】Yahoo Programming Contest 2019

    A - Anti-Adjacency K <= (N + 1) / 2 #include <bits/stdc++.h> #define fi first #define se se ...

  4. C# 反编译防范

    C# 编写的代码通过VS编译器生成 dll 或 exe ,很容易被一些反编译工具查看到源码或对源码进行修改.为防止代码被反编译或被篡改,我们可以进行一定的防范措施.但不能杜绝,因为DotNet编写代码 ...

  5. Linux学习之常用权限管理命令(二)

    (一)常用权限管理命令 (1)chmod命令 (2)chown (3)chgrp (4)umask (一)常用权限管理命令 (1)chmod命令 命令名称:chmod命令英文原意:change the ...

  6. 2-sat-总结+例题

    https://www.cnblogs.com/31415926535x/p/10644419.html 从寒假就开始准备学2sat,,然后当时了解了一下模板就溜了,,,一直到上个星期,,三月底才好好 ...

  7. 【Java】同步阻塞式(BIO)TCP通信

    TCP BIO 背景 网络编程的基本模型是Clien/Server模型,也就是两个进程之间进行相互通信,其中服务端提供位置信息(绑定的IP地址和监听端口),客户端通过连接操作向服务端监听的地址发起连接 ...

  8. 在网站中使用Bing Translator插件翻译文章。

    前一阵子给项目增加了翻译的功能,用的是Bing Translator Widget,今天看见有个兄弟写自定义自己的博客,我就尝试着把这个插件加到了自己的博客中.还真的好用.大家先看下效果,觉得好的请继 ...

  9. javascript高级部分

    回顾 回顾: 整体: - HTML - CSS - JavaScript - 基本数据类型 - for,while.. - DOM - obj = document.getElementById('. ...

  10. Leetcode分类总结(Greedy)

    贪心类题目目前除了正则匹配(Wildcard Matching)(据说其实是DP)那道还没做其他的免费题目都做了,简单做个总结. 贪心的奥义就是每一步都选择当前回合”可见范围“(即可得知的信息)内的最 ...