Kotlin按范围内的值对数组进行排序 [英] Kotlin sort array by value in range

查看:630
本文介绍了Kotlin按范围内的值对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们有一个class Player(val position: Int, val time: Float),我们想按positionplayers的数组或列表进行排序.如果某些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.

推荐答案

您可以先按positiontime进行排序,然后使用标准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 }

说明

  1. compareBy
  2. 通过Playerposition
  3. 对其进行分组
  1. sort the Array by the Player's position and time with sortedWith + compareBy
  2. group it by the Player's position

结果

结果为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆