Can i do something like this in kotlin? ```product...
# announcements
s
Can i do something like this in kotlin?
Copy code
products.sort {
            a,b -> }
a
what exactly are you trying to do?
s
i need to sort two elements by distance
and i have latitude and longitude variables
g
Depends on case. There are sortedBy, sortedWith, sortBy, sortWith. extensions
sorted and sort versions are different, one returns copy of collection, another sorts mutable collection
probably you need something like:
Copy code
products.sortWith(Comparator { a, b ->  })
s
thanks
g
But if your collection element implements Comparable, you can just do something like:
Copy code
products.sortBy { it.distance }
or
Copy code
products.sortBy { it.location }
but distance or location must be Comparable
s
Copy code
val productLocation = Location()
            productLocation.latitude = it.address!!.latitude
            productLocation.longitude = it.address!!.longitude
            mLocationManager.distanceTo(productLocation, androidLocation)
this was my solution
thank you
but it´s nice learn how to use comparator
g
you can also convert location to distance (or some object with distance) using
map
and than sort just by distance. Because calculating distnace on each comparasion doesn’t looks like an efficient way to do that (you have much more comparisons than items in your list)
👍 2