Issue
I have a public class defined in Kotlin: public class Edge(val v: Int, val u: Int, val weight: Double) that helps me define weighted edges of a graph.
Now, in another class, I need to make a list, which I defined as var Sides = mutableListOf<Edge>() but I need to order the list in ascending order which depends on the third parameter of Edge (which is weight). So that if I have the list:
Sides = {Edge(4, 8, 4.1), Edge(20, 9, 7.5), Edge(5, 4, 0.0)}, it becomes:
Sides = {Edge(5, 4, 0.0), Edge(4, 8, 4.1), Edge(20, 9, 7.5)}
Is there any function like .sort() I can use to order this list? or do I have to manually make a function of a sorting method for this?
Thanks in advance
Solution
For a mutable collection like MutableList, you can use the sortBy function to sort the original list itself.
sides.sortBy { it.weight }
And, if you have an immutable collection like List, you can use the sortedBy function which returns a new sorted list.
val sortedList = sides.sortedBy { it.weight }
Also, you have sortByDescending and sortedByDescending for sorting in descending order.
Answered By - Arpit Shukla
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.