scala sortBy and sortWith
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)
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的更多相关文章
- Scala里面的排序函数的使用
排序方法在实际的应用场景中非常常见,Scala里面有三种排序方法,分别是: sorted,sortBy ,sortWith 分别介绍下他们的功能: (1)sorted 对一个集合进行自然排序,通过传递 ...
- Scala数据结构(二)
一.集合的基础操作 1,head头信息 //获取集合的第一个元素 val list = List(,,) list.head // 2,tail尾信息 //获取集合除去头元素之外的所有元素 val l ...
- Scala List的排序函数sortWith
//原始方法: //val list=List("abc","bcd","cde") scala> list.sortWith( (s ...
- [Ramda] Sort, SortBy, SortWith in Ramda
The difference between sort, sortBy, sortWith is that: 1. sort: take function as args. 2. sortBy: ta ...
- Scala中sortBy和Spark中sortBy区别
Scala中sortBy是以方法的形式存在的,并且是作用在Array或List集合排序上,并且这个sortBy默认只能升序,除非实现隐式转换或调用reverse方法才能实现降序,Spark中sortB ...
- Scala比较器:Ordered与Ordering
在项目中,我们常常会遇到排序(或比较)需求,比如:对一个Person类 case class Person(name: String, age: Int) { override def toStrin ...
- Scala HandBook
目录[-] 1. Scala有多cool 1.1. 速度! 1.2. 易用的数据结构 1.3. OOP+FP 1.4. 动态+静态 1.5. DSL 1.6 ...
- 快学scala
scala 1. scala的由来 scala是一门多范式的编程语言,一种类似java的编程语言[2] ,设计初衷是要集成面向对象编程和函数式编程的各种特性. java和c++的进化速度已经大不如 ...
- Scala 运算符和集合转换操作示例
Scala是数据挖掘算法领域最有力的编程语言之一,语言本身是面向函数,这也符合了数据挖掘算法的常用场景:在原始数据集上应用一系列的变换,语言本身也对集合操作提供了众多强大的函数,本文将以List类型为 ...
随机推荐
- 02_kettle插件开发
先下载标准插件模板 地址 http://www.ahuoo.com/download/TemplateStepPlugin.rar 将下载的jar包解压后 导入eclipse项目中 有 ...
- 【C++ Primer 第10章】 1.概述(算法总结)
泛型算法 find(vec.beign(), vec.end(), val) //返回指向第一个给定值的元素的迭代器 count(vec.bengin(), vec.end(), val) //返回给 ...
- C 几何水题 求不同斜率的数目 枚举+set
Description Master LU 非常喜欢数学,现在有个问题:在二维空间上一共有n个点,LU每连接两个点,就会确定一条直线,对应有一个斜率.现在LU把平面内所有点中任意两点连线,得到的斜率放 ...
- python的selenium
from selenium import webdriverChromeDriver="C:\Program Files (x86)\Google\Chrome\Application\ch ...
- Codeforces 295C Greg and Friends BFS
Greg and Friends BFS的过程中维护一下方案数. 我个人感觉不是很好想, 但是写出来之后怎么感觉这题这么SB啊啊. #include<bits/stdc++.h> #def ...
- width:100vh与min-height:calc(100vh + 51px)
vh:相对于视窗的高度,那么vw:则是相对于视窗的高度. “视区”所指为浏览器内部的可视区域大小,即window.innerWidth/window.innerHeight大小,不包含任务栏标题栏以及 ...
- 6-3 二叉树的重建 uva536
已知先序和中序 求后序 可以有两种方式输出 一种是建好树按照树输出 一种是不建树 在遍历的过程中存入vector 再倒叙输出 #include<bits/stdc++.h> usin ...
- HDU 6114 Chess【逆元+组合数】(组合数模板题)
<题目链接> 题目大意: 車是中国象棋中的一种棋子,它能攻击同一行或同一列中没有其他棋子阻隔的棋子.一天,小度在棋盘上摆起了许多車……他想知道,在一共N×M个点的矩形棋盘中摆最多个数的車使 ...
- POJ 2752 (kmp求所有公共前后缀长度)
<题目链接> <转载于> 题目大意: 给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀.从小到大依次输出这些子串的长度.即输出该 ...
- 洛谷 P1002 过河卒 【棋盘dp】
题目链接:https://www.luogu.org/problemnew/show/P1002 题目描述 棋盘上A点有一个过河卒,需要走到目标B点.卒行走的规则:可以向下.或者向右.同时在棋盘上C点 ...