如何 select 列表中每种类型的最后一个元素并按特定顺序将其移动到列表的末尾?

How to select the last element of each type with in a list and move it at the end of the list in a sepcific order?

正在寻找一种功能更简洁、更优化的方法来实现以下输出。

输入=不同类型的玩家列表。 Output = 取出每种类型的最后一个元素并将其附加到列表的末尾。

    data class Player(val id: Int, val type: Int)

    val players = listOf<Player>(
        Player(1, 1),
        Player(2, 1),
        Player(3, 2),
        Player(4, 2),
        Player(5, 2),
        Player(6, 2),
        Player(7, 2),
        Player(8, 3),
        Player(9, 3),
        Player(10, 3),
        Player(11, 3),
        Player(12, 3),
        Player(13, 4),
        Player(14, 4),
        Player(15, 4)
    )
    val subs = mutableListOf<Player>()
    subs.add(players.last { it.type == 1 })
    subs.add(players.last { it.type == 2 })
    subs.add(players.last { it.type == 3 })
    subs.add(players.last { it.type == 4 })

    val mainTeamPlayers = players.minus(subs) 
    val finalTeam = mainTeamPlayers + subs
    
    println(finalTeam)
    
}```

不确定是否更好,但我相信您可以像这样以更紧凑的方式创建订阅者列表:

val subs = players.associateBy { it.type }.map { it.value }.sortedBy { it.type }

如果 players 列表已经保证按类型排序,就像您在示例中所做的那样,您不需要添加最后一个 sortedBy

如@Sweeper 所述,您还可以像这样在一行中获得 finalTeam

val finalTeam = players.associateBy { it.type }.map { it.value }.sortedBy { it.type }.let { (players - it) + it }