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

Time:11-14

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

CodePudding user response:

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 }

CodePudding user response:

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.

  • Related