Kotlin sort array by value in range

别来无恙 提交于 2019-12-08 01:22:48

问题


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.

I know about

list.sortedWith(compareBy<Foo> { it.a }.thenByDescending { it.b }.thenBy { it.c })

But of course it does not solve this case.

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.


回答1:


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)]
    }


来源:https://stackoverflow.com/questions/45903816/kotlin-sort-array-by-value-in-range

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