Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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.

like image 693
Vikas Acharya Avatar asked Apr 14 '20 12:04

Vikas Acharya


People also ask

How do you use kotlin sortWith?

Because the sortWith will do the sorting in-place, we need to use a mutable collection. If we want the result returned as a new collection then we need to use the sortedWith method instead of the sortWith method. For descending order, we can use the reverse method or alternatively define the right Comparator.


1 Answers

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.

like image 146
Vikas Acharya Avatar answered Sep 30 '22 03:09

Vikas Acharya