Kotlin 中的比较

问题描述 投票:0回答:1

我是 Kotlin 的初学者,我正在尝试学习比较,所以我写了这段代码:

fun main (){
    val laptops = mutableListOf(
    laptop(2020,8,1000),
    laptop (2022,4,800),
    laptop(2021,16,600)
    )
    laptops.sortedWith(compareBy<laptop>{it.year}.thenBy {it.price}).forEach{print ("${it} \n")}
}

data class laptop (var year:Int , var ram:Int , var price :Int){}

我假设它会先按年份排序,然后按价格排序,但是当执行代码时,它仅根据年份对它们排序。但我不明白为什么? 提前谢谢你!!

在上面的代码中我期望得到两个结果

kotlin comparison comparator comparable
1个回答
0
投票

您的测试用例不完整,因为输入数据中的笔记本电脑对象都有不同的年份值,因此您永远看不到二次排序。添加与另一个年份相同的一个,例如

val laptops = mutableListOf(
    laptop (2022,4,1000),
    laptop(2020,8,1000),
    laptop (2022,4,800),
    laptop(2021,16,600)
    )

显示预期结果。

© www.soinside.com 2019 - 2024. All rights reserved.