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类型为 ...
随机推荐
- sum of powers
题意: 考虑所有的可重集{a1,a2,a3....ak} 满足a1+a2+....+ak=n,求所有a1^m+a2^m+a3^m的和 n,m,k<=5000 题解: part1: 考虑f[i][ ...
- linux下安装openoffice
一.环境 centos6.9 安装jdk1.6及以上 二.安装依赖 yum install libXext.x86_64 -y yum install freetype -y yum groupins ...
- Unity3D 中的面向对象设计 {游戏对象(创建、删除、获取),以及添加修改组件}
一.创建游戏对象 游戏对象分三种:(1) 将物体模型等资源由Project工程面板拖拽到Hierarchy层次面板中 (2) 由GameObject菜单创建Unity自带的游戏对象,如Cube.Cam ...
- 类的 __call__ 和__repr__ 方法
__call__: 让类实例可以被调用: __str__ , __repr__ : 两个都能是类实例名能被打印,区别在于repr可在交互是直接打印类名不用加print
- phpunit
教程及文档: https://www.jianshu.com/p/abcca5aa3ad6 http://www.phpunit.cn/manual/current/zh_cn/phpunit-boo ...
- 【原创】ABP之IConventionalDependencyRegistra接口分析
类图: 作用: abp中默认把对象的注册分为5中约定注册方式: 1.AbpAspNetCoreConventionalRegistrar public class AbpAspNetCoreConve ...
- OpenStack容器网络项目Kuryr(libnetwork)
转:https://www.aliyun.com/jiaocheng/518375.html 摘要:容器近几年非常流行,有很多项目都考虑将容器与SDN结合.Kuryr就是其中一个项目.Kuryr项目在 ...
- php插入上万条mysql数据最快的方法
1.使用thinkphp框架 先生成包含所有数据的数组,再使用 addAll() 方法,插入1万条数据仅需3秒钟. 2.PHP原始方法: 将SQL语句进行拼接,使用 insert into table ...
- Codeforces.100633J.Ceizenpok's formula(扩展Lucas)
题目链接 ->扩展Lucas //求C_n^k%m #include <cstdio> typedef long long LL; LL FP(LL x,LL k,LL p) { L ...
- Wannafly挑战赛25游记
Wannafly挑战赛25游记 A - 因子 题目大意: 令\(x=n!(n\le10^{12})\),给定一大于\(1\)的正整数\(p(p\le10000)\)求一个\(k\)使得\(p^k|x\ ...