what is the difference between sortBy - sortedBy and sortWith - sortedWith in kotlin

喜你入骨 提交于 2020-07-21 06:31:30

问题


I'm just exploring kotlin collection and I observed one important behavior.


val sports = listOf<Sports>(
        Sports("cricket", "7"),
        Sports("gilli", "10"),
        Sports("lagori", "8"),
        Sports("goli", "6"),
        Sports("dabba", "4")
    )

    sports.sortedBy { it.rating } // sortedByDescending is to sort in descending
        .forEach({ println("${it.name} ${it.rating}") })


}

class Sports(name: String, rating: String) {
    var name: String = name
    var rating: String = rating
}

above I can only get sortedBy method i.e which starts with sorted. I don't know why I'm not getting sortBy and sortWith operations.

can anyone give explanation for this in simple words.


回答1:


Ok, this seems to be silly question. But, sometimes even for experienced people struggled with this. So, I'll answer this

First point, There are two list types. listOf, mutableListOf

So, if you need sortBy, sortWith or anything which starts with sort then you must use mutableListOf

  • sort will be applied on original list. but not return anything.
  • sorted will not change original list but returns new list after applying changes.

if you want to keep original list of elements unchanged go with sorted stuff or choose sort stuff.



来源:https://stackoverflow.com/questions/61208049/what-is-the-difference-between-sortby-sortedby-and-sortwith-sortedwith-in-ko

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!