Kotlin sort array by value in range

感情迁移 提交于 2019-12-06 11:19:47

You could first sort by position and time and then group by time with standard Kotlin functionality.

Example

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 }

Description

  1. sort the Array by the Player's position and time with sortedWith + compareBy
  2. group it by the Player's position

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)]
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!