Home > Software engineering >  How to sort a list by the closest value to another variable Kotlin
How to sort a list by the closest value to another variable Kotlin

Time:08-31

I want to sort a list of elements by comparing the distance between their variables to a fixed variable that I have. My variable is the current coordinates of my device. Something like that:

class Location(var lat: Double, var Long:Double)
myLocation = Location(-33.07216, -36.70315)
val locations = mutableListOf(Location(-23.23018, -48.50247),Location(8.3334, 49.04748),Location(61.82096, 50.45373))

And I have a list containing several of these Classes. I want to sort the list based on the Classes that are closest to my current location How can I do this? I'm pretty lost with Comparator, SortBy and SortWith

CodePudding user response:

sortWith is for using a Comparator class. You will typically use that only when you're setting up complex relations, like sorting by one thing followed by another thing in case of a tie on the first thing.

sortBy lets you write a simple lambda that selects a value that it will use to compare the items. In this case, you want to sort by distance to a location, so your lambda should return that distance.

locations.sortBy { it.distanceTo(myLocation) }

If you want farthest distances first, use sortByDescending instead.

  • Related