误用 Kotlin 中的 sortedWith() 方法排序,集合没有变化
时间:2019年8月4日14:17:06
问题描述:
看下边的小例子:
data class Man(val name: String, val age: Int, val type: Int)
fun main(args: Array<String>) {
val list = mutableListOf<Man>()
list.add(Man("wzc", 31,2))
list.add(Man("wzj", 32,1))
list.add(Man("wcx", 3,1))
list.add(Man("wcg", 7,1))
println("before sort")
for (man in list) {
println(man)
}
list.sortedWith(Comparator {lh, rh ->
if (lh.type.compareTo(rh.type) == 0) {
lh.age.compareTo(rh.age)
} else {
lh.type.compareTo(rh.type)
}
})
println("after sort")
for (man in list) {
println(man)
}
}
/*
打印结果:
before sort
Man(name=wzc, age=31, type=2)
Man(name=wzj, age=32, type=1)
Man(name=wcx, age=3, type=1)
Man(name=wcg, age=7, type=1)
after sort
Man(name=wzc, age=31, type=2)
Man(name=wzj, age=32, type=1)
Man(name=wcx, age=3, type=1)
Man(name=wcg, age=7, type=1)
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
可以看到排序前后,打出的内容没有丝毫变化。
解决方法:
看一下 sortedWith 的代码:
/**
* Returns a list of all elements sorted according to the specified [comparator].
*
* The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
*/
public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T> {
if (this is Collection) {
if (size <= 1) return this.toList()
@Suppress("UNCHECKED_CAST")
return (toTypedArray<Any?>() as Array<T>).apply { sortWith(comparator) }.asList()
}
return toMutableList().apply { sortWith(comparator) }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
可以排序后的结果是在返回值里面。
修改代码:
data class Man(val name: String, val age: Int, val type: Int)
fun main(args: Array<String>) {
val list = mutableListOf<Man>()
list.add(Man("wzc", 31,2))
list.add(Man("wzj", 32,1))
list.add(Man("wcx", 3,1))
list.add(Man("wcg", 7,1))
println("before sort")
for (man in list) {
println(man)
}
// list.sortedWith(Comparator {lh, rh ->
// if (lh.type.compareTo(rh.type) == 0) {
// lh.age.compareTo(rh.age)
// } else {
// lh.type.compareTo(rh.type)
// }
// })
// println("after sort")
// for (man in list) {
// println(man)(http://www.my516.com)
// }
val sortedWith = list.sortedWith(Comparator { lh, rh ->
if (lh.type.compareTo(rh.type) == 0) {
lh.age.compareTo(rh.age)
} else {
lh.type.compareTo(rh.type)
}
})
list.clear()
list.addAll(sortedWith)
println("after sort")
for (man in list) {
println(man)
}
}
/*
打印结果:
before sort
Man(name=wzc, age=31, type=2)
Man(name=wzj, age=32, type=1)
Man(name=wcx, age=3, type=1)
Man(name=wcg, age=7, type=1)
after sort
Man(name=wcx, age=3, type=1)
Man(name=wcg, age=7, type=1)
Man(name=wzj, age=32, type=1)
Man(name=wzc, age=31, type=2)
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
可以看到,正常排序了。可以看到还有个 sortWith 方法:
expect fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit
1
二者的区别是:sortedWith() 方法可以通过 Iterable 对象调用,排序结果在返回值里;而 sortWith() 方法只能通过 MutableList 来调用,排序结果不在返回值里,而是直接在调用对象里了。sortedWith() 方法内部最终还是调用 sortWith() 方法来排序的。
误用 Kotlin 中的 sortedWith() 方法排序,集合没有变化的更多相关文章
- str中的join方法; set集合;深浅拷贝
一.str中的join方法 1,用join可以吧列表转换为字符串 将列表转换成字符串. 每个元素之间用_拼接 s = "_". join(['德玛', ''赵信'', '易']) ...
- 千万不要误用 java 中的 HashCode 方法
刚才debug追堆栈的时候发现一个很奇怪的问题 我用IE8和Google的浏览器访问同一个地址 Action的 scope="session" 也设置了 而且两个浏览器提交的参数m ...
- java中Collections.sort()方法实现集合排序
1.Integer/String泛型的List进行排序 List <Integer> integerlist = new ArrayList<Integer>(); //定 ...
- 关于Kotlin中日志的使用方法
1 引言 想必学过Java的人都知道一个@Slf4j使用得多么的舒服: @Slf4j public class TestController{ @GetMapping("/test" ...
- Day07_39_集合中的remove()方法 与 迭代器中的remove()方法
集合中的remove()方法 与 迭代器中的remove()方法 深入remove()方法 iterator 中的remove()方法 collection 中的remove(Object)方法 注意 ...
- 【转载】 C#中List集合使用OrderByDescending方法对集合进行倒序排序
在C#的List集合操作中,有时候需要针对List集合进行排序操作,如果是对List集合按照元素对象或者元素对象的某个属性进行倒序排序的话,可以使用OrderByDescending方法来实现,Ord ...
- Kotlin中功能操作与集合(KAD 11)
作者:Antonio Leiva 时间:Feb 2, 2017 原文链接:https://antonioleiva.com/functional-operations-collections-kotl ...
- 对list集合中的对象进行排序(转载)
原文链接:http://blog.csdn.net/veryisjava/article/details/51675036 Collections对List集合中的数据进行排序 有时候需要对集合中的元 ...
- hashCode()方法以及集合中Set的一些总结
一.前言 本篇文章没有什么主题,就是一些零散点的总结.周末没事看了几道蚂蚁金服的面试题,其中有好几道都是特别简单的,基础性的题目,就是我们平时用到的,但是发现要是完全说出来还是有一些不清楚的地方,所以 ...
随机推荐
- YII框架微信公众号
<?phpnamespace backend\controllers; use yii\db\Query;use yii\web\Controller;use Yii;class Exam2Co ...
- javaweb:关于HttpServletResponse介绍 (转)
出处: https://www.cnblogs.com/xdp-gacl/p/3789624.html Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request ...
- Almost Increasing Array CodeForces - 946G (dp)
大意: 定义几乎递增序列为删除不超过一个数后序列严格递增. 给定序列, 求最少改变多少个数能变为几乎递增序列. 跟hdu5256类似,
- C#/.NET/.NET Core定时任务调度的方法或者组件有哪些--Timer,FluentScheduler还是...
原文:C#/.NET/.NET Core定时任务调度的方法或者组件有哪些--Timer,FluentScheduler还是... 原文由Rector首发于 码友网 之 <C#/.NET/.NET ...
- 定义一个接口CanFly,描述会飞的方法public void fly();
1.使用类与接口的知识完成如下要求:(1)定义一个接口CanFly,描述会飞的方法public void fly();(2)分别定义类飞机和鸟,实现CanFly接口.(3)定义一个测试类,测试飞机和鸟 ...
- 手把手教你如何安装使用webpack vue cli
1.安装node.js:https://nodejs.org/en/download/(看电脑的系统是多少位下载相应版本) 我下载的是Windows Installer(.msi) x64 2.打开c ...
- vue学习【四】vuex快速入门
大家好,我是一叶,今天我们继续踩坑.今天的内容是vuex快速入门,页面传值不多的话,不建议vuex,直接props进行父子间传值就行,使用vuex就显得比较臃肿. 我们先预览一下效果,如图1所示. 图 ...
- 在浏览器输入url,发生了什么?BSC结构图(百度搜索关键字发生了什么?)
服务器---------->软件(客户端) 百度搜索周杰伦,发生了什么
- 【leetcode 136】136. Single Number
要求:给定一个整数数组,除了其中1个元素之外,其他元素都会出现两次.找出这个只出现1次的元素. 例: array =[3,3,2,2,1] 找出元素1. 思路:最开始的想法是用两次for循环,拿 ...
- Java动态加载类
详见:https://blog.csdn.net/zai_xia/article/details/80026325 扩展:java反射机制与动态加载类 https://www.cnblogs.com/ ...