Kotlin sort array by value in range

2019-05-28 19:59发布

问题:

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