Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin: sort List<T> with T being a class

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

like image 841
vale383 Avatar asked Dec 22 '22 15:12

vale383


2 Answers

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.

like image 149
Arpit Shukla Avatar answered Jan 07 '23 15:01

Arpit Shukla


You're looking for sortBy. Given a list of T, sortBy takes a mapping function from T to R (where R is some type which has an ordering defined on it). Consider

Sides.sortBy { n -> n.weight }
like image 26
Silvio Mayolo Avatar answered Jan 07 '23 15:01

Silvio Mayolo