天天看点

误用 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")

}

/*

打印结果:

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

*/

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) }

可以排序后的结果是在返回值里面。

修改代码: