时间: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() 方法排序,集合没有变化的更多相关文章

  1. str中的join方法; set集合;深浅拷贝

    一.str中的join方法 1,用join可以吧列表转换为字符串 将列表转换成字符串. 每个元素之间用_拼接 s = "_". join(['德玛', ''赵信'', '易']) ...

  2. 千万不要误用 java 中的 HashCode 方法

    刚才debug追堆栈的时候发现一个很奇怪的问题 我用IE8和Google的浏览器访问同一个地址 Action的 scope="session" 也设置了 而且两个浏览器提交的参数m ...

  3. java中Collections.sort()方法实现集合排序

    1.Integer/String泛型的List进行排序 List <Integer> integerlist = new ArrayList<Integer>();   //定 ...

  4. 关于Kotlin中日志的使用方法

    1 引言 想必学过Java的人都知道一个@Slf4j使用得多么的舒服: @Slf4j public class TestController{ @GetMapping("/test" ...

  5. Day07_39_集合中的remove()方法 与 迭代器中的remove()方法

    集合中的remove()方法 与 迭代器中的remove()方法 深入remove()方法 iterator 中的remove()方法 collection 中的remove(Object)方法 注意 ...

  6. 【转载】 C#中List集合使用OrderByDescending方法对集合进行倒序排序

    在C#的List集合操作中,有时候需要针对List集合进行排序操作,如果是对List集合按照元素对象或者元素对象的某个属性进行倒序排序的话,可以使用OrderByDescending方法来实现,Ord ...

  7. Kotlin中功能操作与集合(KAD 11)

    作者:Antonio Leiva 时间:Feb 2, 2017 原文链接:https://antonioleiva.com/functional-operations-collections-kotl ...

  8. 对list集合中的对象进行排序(转载)

    原文链接:http://blog.csdn.net/veryisjava/article/details/51675036 Collections对List集合中的数据进行排序 有时候需要对集合中的元 ...

  9. hashCode()方法以及集合中Set的一些总结

    一.前言 本篇文章没有什么主题,就是一些零散点的总结.周末没事看了几道蚂蚁金服的面试题,其中有好几道都是特别简单的,基础性的题目,就是我们平时用到的,但是发现要是完全说出来还是有一些不清楚的地方,所以 ...

随机推荐

  1. PHP常用代码片段

    /** * 高效判断远程文件是否存在 * @param $file * @return bool 存在返回 true 不存在或者其他原因返回false */ function remoteFileEx ...

  2. 解决sudo用户找不到环境变量的问题

    出于安全方面的考虑,使用sudo执行命令将在一个最小化的环境中执行,环境变量都重置成默认状态.所以PATH这个变量不包括用户自定义设置的内容 在sudo用户的主目录里的.bashrc中添加如下内容即可 ...

  3. ckfinder的使用

    引入<script type="text/javascript" src="${ctxStatic}/ckfinder/ckfinder.js">& ...

  4. IDEA一些有用的功能

    使用 Type Info 如果你想要更多的关于符号的信息,例如从哪里或它的类型是什么, 快速文档可以很好的帮到您,您可以按下 Ctrl+Q 来调用它,然后你会看到一个包含这些细节的弹出窗口.如果您不需 ...

  5. C++ 大数运算(加减乘除取模)

    加法:(字符串模拟小学加法) string add(string s1, string s2) { int len1 = s1.length(), len2 = s2.length(); ; '); ...

  6. 优化 Karatsuba 乘法(老物)

    虽然写好了我自己用的a*启发函数但还是有些不尽人意,如果通过数学分析确定不出问题可以工作了的话应该就会发出来了 // Karatsuba 递归式距离推导 // h(x) = f(x) * g(x):/ ...

  7. ajax跨域jsonp —— javascript

    目录 jsonp是什么 jsonp原理 原生js使用jsonp jquery使用jsonp jsonp是什么 jsonp作用:解决跨域问题 为什么有跨域问题? “同源策略限制了从同一个源加载的文档或脚 ...

  8. 使用CXF开发WebService程序的总结(四):基于bean的客户端和服务端代码的编写

    1. 在原服务端项目 ws_server中添加两个bean 1.1 添加两个类  User 和 Clazz   package com.lonely.pojo; public class User { ...

  9. 22_3mybaits——连接池

    1.连接池 我们在实际开发中都会使用连接池. 因为它可以减少我们获取连接所消耗的时间. 2.mybatis中的连接池 mybatis连接池提供了3种方式的配置: 配置的位置: 主配置文件SqlMapC ...

  10. D Merge Equals Educational Codeforces Round 42 (Rated for Div. 2) (STL )

    D. Merge Equals time limit per test2 seconds memory limit per test256 megabytes inputstandard input ...