简体   繁体   English

如何按最接近另一个变量 Kotlin 的值对列表进行排序

[英]How to sort a list by the closest value to another variable Kotlin

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我对 Comparator、SortBy 和 SortWith 很迷茫

sortWith is for using a Comparator class. sortWith用于使用比较器 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. sortBy允许您编写一个简单的 lambda 来选择一个用于比较项目的值。 In this case, you want to sort by distance to a location, so your lambda should return that distance.在这种情况下,您希望按到某个位置的距离排序,因此您的 lambda 应该返回该距离。

locations.sortBy { it.distanceTo(myLocation) }

If you want farthest distances first, use sortByDescending instead.如果您首先想要最远的距离,请改用sortByDescending

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM