Kotlin按范围内的值对数组进行排序 [英] Kotlin sort array by value in range
问题描述
让我们有一个class Player(val position: Int, val time: Float)
,我们想按position
对players
的数组或列表进行排序.如果某些players
在第一次排序后具有相同的position
,我们想按time
在组中对它们进行排序.按组,我是指一组具有相同位置的players
.
Let's have a class Player(val position: Int, val time: Float)
and we want to sort an array or list of players
by position
. If some of these players
have the same position
after first sorting, we want to sort them by time
in groups. By group I mean set of players
with the same position.
我知道
list.sortedWith(compareBy<Foo> { it.a }.thenByDescending { it.b }.thenBy { it.c })
但是,它当然不能解决这种情况.
But of course it does not solve this case.
在Kotlin中,有什么聪明的方法可以完成这项简单的任务?我们可以通过检查位置和交换项目来对其进行手动排序,但我想知道在这种情况下Kotlin是否有话要说.
Is there any smart way in Kotlin to achieve this simple task? We can sort it manually by checking positions and swapping items, but I wonder if Kotlin has something to say in this case.
推荐答案
您可以先按position
和time
进行排序,然后使用标准Kotlin功能按time
进行分组.
You could first sort by position
and time
and then group by time
with standard Kotlin functionality.
data class Player(val position: Int, val time: Float)
val p1 = Player(1, 10f)
val plys = arrayOf(p1, p1.copy(position = 3),
p1.copy(time = 0f), p1.copy(time = 20f),
p1.copy(position = 2), p1.copy(position = 2, time = 20f))
val groupBy = plys.sortedWith(compareBy(Player::position, Player::time))
.groupBy { it.position }
说明
- 用
compareBy
- 通过
Player
的position
对其进行分组
- sort the
Array
by thePlayer
'sposition
andtime
withsortedWith
+compareBy
- group it by the
Player
'sposition
结果
结果为Map<Int,List<Player>
,在示例中如下所示:
Result
The result is a Map<Int,List<Player>
, which in the example looks like this:
{
1=[Player(position=1, time=0.0), Player(position=1, time=10.0), Player(position=1, time=20.0)],
2=[Player(position=2, time=10.0), Player(position=2, time=20.0)],
3=[Player(position=3, time=10.0)]
}
这篇关于Kotlin按范围内的值对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!