Reputation: 271
This is my data
val data = ArrayList<Product>()
data.add(Product(it=1,type = "Ait 45"))
data.add(Product(it=2,type = "Ait 35"))
data.add(Product(it=3,type = "Ait 65"))
data.add(Product(it=4,type = "Ait 325"))
data.add(Product(it=5,type = "Ait 42"))
I am trying sort data based on type in descending order which is string type
expected output after sort
data should = {(it=2,type = "Ait 35"),(it=5,type = "Ait 42"),(it=1,type = "Ait 45"),(it=3,type = "Ait 65"),(it=4,type = "Ait 325")}
Please help me how to sort item using sort method in kotlin
Upvotes: 0
Views: 1113
Reputation: 8457
You can use List<T>.sortedBy()
function from the standard library which returns a new list with the sorted elements or MutableList<T>.sortBy()
which sorts the elements in-place (moves the current list's items around to sort them).
Both of these functions sortedBy
and sortBy
have their sortedByDescending
and sortByDescending
counterparts.
Note that the following code will sort the strings by text, if you want to sort by the integer value contained into the "type" string you'd need to convert that value into an integer by manipulating the string contents.
data class Product(val it: Int,val type: String)
fun main() {
val data = ArrayList<Product>()
data.add(Product(it=1,type = "Ait 45"))
data.add(Product(it=2,type = "Ait 35"))
data.add(Product(it=3,type = "Ait 65"))
data.add(Product(it=4,type = "Ait 325"))
data.add(Product(it=5,type = "Ait 42"))
println(data.sortedBy { it.type})
println(data.sortedByDescending { it.type})
}
See the code in action inside the Kotlin playground
Upvotes: 1